[英]Load/Save GUI game — NoSuchElementException error
我對在Java中使用GUI和JPanel非常陌生。 現在,我正在開發一個可以保存和加載的游戲。 保存后,它需要一個JArray,並根據是否在某處或某張圖片上沒有任何內容,將0、1、2 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()==#)處。 我確保文件中也有一個整數。
您應該正確保存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 .......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.