从键盘输入读取二维数组
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入二维数组的行数:");
int rows = scanner.nextInt();
System.out.println("请输入二维数组的列数:");
int cols = scanner.nextInt();
int[][] array = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.println("请输入第" + (i + 1) + "行,第" + (j + 1) + "列的元素:");
array[i][j] = scanner.nextInt();
}
}
// 打印二维数组
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println();
}
}
}
从文件读取二维数组
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
int[][] array = new int;
try {
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
String line = br.readLine();
String[] values = line.split(" ");
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
array[i][j] = Integer.parseInt(values[i * array[i].length + j]);
}
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
// 打印二维数组
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println();
}
}
}
在上面的代码中,`input.txt`文件应该包含以空格分隔的整数,例如:
1 2 3 4
5 6 7 8