我知道这是一个常见问题,但是,即使在进行研究之后,我也不确定为什么会出现错误。
import java.io.*;
import java.util.*;
public class readfile {
private Scanner x;
public void openFile(){
try{
x = new Scanner(new File("input.txt"));
}
catch(Exception e){
System.out.println("Oh noes, the file has not been founddd!");
}
}
public void readFile(){
int n = 0;
n = Integer.parseInt(x.next()); //n is the integer on the first line that creates boundaries n x n in an array.
System.out.println("Your array is size ["+ n + "] by [" + n +"]");
//Create n by n array.
int[][] array = new int[n][n];
//While there is an element, assign array[i][j] = the next element.
while(x.hasNext()){
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
array[i][j] = Integer.parseInt(x.next());
System.out.printf("%d", array[i][j]);
}
System.out.println();
}
}
}
public void closeFile(){
x.close();
}
}
我正在阅读一个包含邻接矩阵的文本文件,其中第一行表示矩阵的大小。即)第 1 行读取 5。因此我创建了一个 5x5 的二维数组。我遇到的问题是在我阅读并打印文件后,我得到一个 NoSuchElement 异常。提前谢谢!
注意:我很好奇,我已经看到我需要在循环中使用 x.hasNext() ,所以我不假设没有输入时有输入。然而,我已经做到了。不确定是什么问题。
输出:
Your array is size [7] by [7]
0110011
1000000
1001000
0010001
0000001
1000001
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at readfile.readFile(readfile.java:32)
at verticies.main(verticies.java:8)