【发布时间】:2016-03-20 19:45:04
【问题描述】:
我正在尝试从文本文件中读取数据并使用该数据来恢复保存游戏。然而,问题是当它到达从文件中读取的第一行代码时,它会抛出 no such element 异常吗?谁能给我一个暗示为什么会这样。我已经检查了文本文件,并且可以从中读取数据。
下面是使用的代码:
public void readSave() {
int p1Turn = 0;
int p2Turn = 0;
try {
FileReader fr = new FileReader("snorkels.txt");
BufferedReader reader = new BufferedReader(fr);
String line = reader.readLine();
Scanner scan = null;
int playerNumber = 0;
while (line != null) {
scan = new Scanner(line);
playerNumber = scan.nextInt(); // No such element exception
if (playerNumber == 1) {
player1.setName(scan.next());
player1.setColour(scan.next());
p1Turn = scan.nextInt();
}
if(playerNumber == 2){
player2.setName(scan.next());
player2.setColour(scan.next());
p2Turn = scan.nextInt();
}
line = reader.readLine();
}
reader.close();
} catch (FileNotFoundException e) {
System.out.println("Couldnae find the file");
} catch (IOException e) {
System.out.println("Wee problem reading from file");
}
}
当我尝试读取第一个 int 时抛出异常。
文本文件包含以下数据:
1 个插孔 P 0
2 人工智能 G 0
【问题讨论】:
-
那是一堵不可读且未格式化的代码墙。没有人会想读那个。请通过How to Ask 和minimal reproducible example。
-
使用调试器,下一行断点,然后查看
line的值。它显然不包含您认为的内容。