我不断收到与扫描 .txt 文件相关的异常 NoSuchElement。导致异常的此类错误是:
"java.util.Scanner.throwFor(Unknown Source)
java.util.Scanner.next(Unknown Source)
java.util.Scanner.nextInt(Unknown Source)"
我所做的只是读取 1 和 0 作为 ASCII 终端游戏中基本地图的测试。
我的代码:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class Adventure {
private Scanner in_file;
private char[][] level;
public Adventure() {
level = new char[5][5];
}
public static void main(String []args) {
Adventure adv = new Adventure();
adv.load_game();
adv.main_game();
}
public void load_game() {
try {
in_file = new Scanner(new File("level.txt"));
} catch (FileNotFoundException e) {
System.err.println("ERROR: Level could not be loaded!");
System.exit(1);
}
for (int i = 0; i < level.length; i++ ) {
for (int j = 0; j < level[i].length; j++) {
if (in_file.hasNextInt()) {
if (in_file.nextInt() == 0)
level[i][j] = '-';
else if (in_file.nextInt() == 1)
level[i][j] = '#';
}
}
}
in_file.close();
}
public void new_game() {
}
public void main_game() {
for (int i = 0; i < 20; i++) {
for (int j = 0; j < 50; j++) {
System.out.print(level[i][j]);
}
}
}
public void save_game() {
}
}
我的文本文件“level.txt”:
11111
10001
10001
10001
11111