手动输入元素
使用两个嵌套的for循环,外层循环遍历行,内层循环遍历列,逐个输入元素。
Scanner input = new Scanner(System.in);
int rows = input.nextInt();
int cols = input.nextInt();
int[][] array = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
array[i][j] = input.nextInt();
}
}
逐行输入
使用`Scanner`类逐行读入元素,并将每行元素分割为单个元素后存储在二维数组中。
Scanner input = new Scanner(System.in);
int rows = input.nextInt();
int cols = input.nextInt();
int[][] array = new int[rows][cols];
for (int i = 0; i < rows; i++) {
String line = input.nextLine();
for (int j = 0; j < cols; j++) {
array[i][j] = Integer.parseInt(line.split(" ")[j]);
}
}
使用`Arrays.deepToString()`方法输出二维数组
import java.util.Arrays;
// ...
char[][] arr = new char[m][n];
// ...
for (int i = 0; i < m; i++) {
String s = input.next();
for (int j = 0; j < n; j++) {
arr[i][j] = s.charAt(j);
}
}
System.out.println(Arrays.deepToString(arr));
请选择适合您需求的方法进行二维数组的输入。