這與Reading 2-D array from a file類似。我試圖在java中將文本文件讀入一個2-D數組中。不同之處在於我需要將它作爲字符串數組而不是ints讀入。 (是的,這是作業。)我能夠讓代碼適用於整數,但是我的文本文件可以包含「*」和「 - 」,這會導致.nextInt()拋出異常。我試過使用.next()將它作爲一個字符串使用空格作爲分隔符。然而這也是從一開始就拋出一個例外。這個問題似乎在readFile函數中。我怎樣才能把每個字符作爲一個字符串?這裏是我的3個功能:從文本文件讀入到java中的二維字符串數組中
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