我非常擅长使用GUI和JPanel与Java。现在我正在开发一款可以保存和加载的游戏。保存时,它需要一个JArray,并且根据某个地方或某个图片是否有任何内容,将0s, 1s, and 2s
保存到文件中。加载时,它会查看0s, 1s, and 2s
并将相应位置(在for循环中)替换为带有图片或没有任何内容。
当我加载游戏时,它几乎不会加载并错误地显示“NoSuchElementException
”。这是我的负担:
public void loadGame() throws FileNotFoundException{
String fileName = JOptionPane.showInputDialog("What is your file's name?") + ".txt";
Scanner reader = new Scanner(new FileReader(fileName));
playerOne = reader.next();
playerTwo = reader.next();
counter = reader.nextInt();
for (int i = 1; i < grid_height-1; i++) {
for (int j = 1; j <= grid_width-1; j++) {
if(reader.nextInt() == 1){game[i][j].setIcon(p1);}
if(reader.nextInt() == 2){game[i][j].setIcon(p2);}
else if(reader.nextInt() == 0){game[i][j].setIcon(null); } } }
reader.close();
}
}
如果需要,我的保存:
public void saveGame() throws FileNotFoundException{
String fileName = JOptionPane.showInputDialog("What will you name your file?") + ".txt";
PrintWriter out = new PrintWriter(fileName);
out.println(playerOne);
out.println(playerTwo);
out.println(counter);
for (int i = 1; i < grid_height-1; i++) {
for (int j = 1; j <= grid_width-1; j++) {
if(game[i][j].getIcon() == null){out.println(0); }
else if(game[i][j].getIcon() == p1){out.println(1);}
else if(game[i][j].getIcon() == p2){out.println(2); }
}
}
out.close();
JOptionPane.showMessageDialog(null, "Saved successfully!", "Saved",
JOptionPane.PLAIN_MESSAGE);
}
非常感谢任何帮助。错误通常在代码中的if(reader.nextInt()==#)处发生。我已经在文件中确定接下来还有一个整数。
答案 0 :(得分:0)
您应该正确保存nextInt的返回值并将其用于比较。
public void loadGame() throws FileNotFoundException{
//your code here ........
for (int i = 1; i < grid_height-1; i++) {
for (int j = 1; j <= grid_width-1; j++) {
if(reader.hasNext()){
int next = reader.nextInt(); //save the return value and use it for comparision
if (next == 1){game[i][j].setIcon(p1);}
if (next == 2){game[i][j].setIcon(p2);}
else if(next == 0){game[i][j].setIcon(null);
} //close the if loop
//rest of your code here .......