我在将文本文件中的矩阵存储到二维数组中时遇到问题。每次我运行以下代码时,它都会执行没有错误,但控制台中不会打印任何内容。任何帮助将不胜感激。我的代码如下所示:
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
最佳答案
问题出在你的第一个循环上,当“input1.txt”
的内容是int
时,最好使用nextInt()
>
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");
}
关于java - 将文本文件中的矩阵存储到二维数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58274538/