これはReading 2-D array from a fileに似ています。私はJavaの2次元配列にテキストファイルを読み込もうとしています。違いは、intの代わりに文字列の配列として読み込む必要があることです。 (これは宿題です)私はintで動作するようにコードを取得できましたが、テキストファイルに "*"と " - "を付けることができ、.nextInt()が例外をスローします。私は区切り文字として空白スペースを使用して文字列としてそれをプルするために.next()を使用しようとしました。しかし、これはまた、最初から例外をスローしています。この問題は、readFile関数にあるようです。各文字を文字列としてどのように取り込むことができますか?ここに私の3つの機能です:テキストファイルをJavaの文字列の2次元配列に読み込む
public static void main(String [] args) {
Scanner s = new Scanner(System.in);
String fileName = ""; //for javac
//obtain file name for puzzle
if(0 == args.length) {
System.out.println("Welcome to the Sudoku Solver.");
System.out.println("Please enter a file name.");
fileName = s.nextLine();
} else if(1 == args.length) {
fileName = args[0];
} else {
System.out.println("You have entered invalid data.");
System.exit(1);
}
//open puzzle file and read puzzle
int m = 0; //for javac
try {
BufferedReader f = new BufferedReader(new FileReader(fileName));
while(f.readLine() != null) {
++m;
}
System.out.println(m);
String[][] theArray;
f.close();
theArray = readFile(m, fileName);
readPuzzle(theArray);
} catch(Exception e) {
System.out.println("An error has occurred...");
}
}
public static void readPuzzle(String [][] thePuzzle) {
for(int r = 0; r < thePuzzle.length; ++r) {
for(int c = 0; c < thePuzzle[r].length; ++c) {
System.out.printf("%7d", thePuzzle[r][c]);
}
System.out.println();
}
System.out.println();
}
public static String[][] readFile(int m, String fileName) {
String[][] theArray = new String[m][m];
try{
Scanner g = new Scanner(new File(fileName));
for(int r = 0; r <= theArray.length; ++r){
for(int c = 0; c <= theArray[r].length; ++c){
if(g.hasNext()){
theArray[r][c] = g.next("\\s+");
}
}
}
} catch(Exception e) {
System.out.println("Error in readFile.");
}
return theArray;
}
テキストファイルには、次のようになります。
5 3 * * 7 * * * *
6 * * 1 9 5 * * *
* 9 8 * * * * 6 *
8 * * * 6 * * * 3
4 * * 8 * 3 * * 1
7 * * * 2 * * * 6
* 6 * * * * * * *
* * * 4 1 9 * * 5
* * * * 8 * * 7 9
私は自分のコードにこれを追加しましたが、私はまだ私はそれを使用しようとするたびにスローされた例外を取得しています。それが例外を投げている理由は何ですか? – wxwatchr