これがよくある質問であることは理解していますが、調査を行ってもエラーが発生する理由がわかりません。
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の2次元配列を作成します。私が抱えている問題は、ファイルを読み取って印刷した後、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)