我无法将文本文件中的矩阵存储到2D数组中。每次我运行以下代码时,它都不会错误执行,但是控制台中不会打印任何内容。任何帮助将不胜感激。我的代码如下所示:
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(new File("input1.txt"));
String [][] array = new String [9][9];
try{
for(int i = 0; i > array.length; i++) {
for(int j = 0; j < array[0].length; j++) {
array[i][j] = sc.next();
System.out.print(array[i][j] + " ");
}
}
}catch(Exception e){
System.out.print("error");
}
这也是我正在阅读的文本文件的内容:
5 3 4 6 7 8 9 1 2
6 7 2 1 9 5 3 4 8
1 9 8 3 4 2 5 6 7
8 5 9 7 6 1 4 2 3
4 2 6 8 5 3 7 9 1
7 1 3 9 2 4 8 5 6
9 6 1 5 3 7 2 8 4
3 4 5 2 8 6 1 7 9
答案 0 :(得分:0)
问题出在您的第一个循环上,而且当nextInt()
的内容为"input1.txt"
时最好使用int
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(new File("input1.txt"));
int [][] array = new int [9][9];
try{
for(int i = 0; i < array.length; i++) {
for(int j = 0; j < array[0].length; j++) {
array[i][j] = sc.nextInt();
System.out.print(array[i][j] + " ");
}
}
}catch(Exception e){
System.out.print("error");
}
答案 1 :(得分:0)
您首先在for循环中出错
Scanner sc = new Scanner(new File("input1.txt"));
String [][] array = new String [9][9];
try{
for(int i = 0; i < array.length; i++) { // your error was here. you wrote int i = 0 i > array.length; i++
for(int j = 0; j < array[0].length; j++) {
array[i][j] = sc.next();
System.out.print(array[i][j] + " ");
}
}
}catch(Exception e){
System.out.print("error");
}