2013-12-09 32 views
0

我对使用GUI和JPanel与Java非常新。现在我正在开发一款可以保存和加载的游戏。保存时,需要一个JArray,并根据某个地方或某张图片中是否没有内容,将0s, 1s, and 2s保存到一个文件中。当它加载时会看到0s, 1s, and 2s,并在相应位置(在for-loop中)用图片或空白替换它们。加载/保存GUI游戏 - NoSuchElementException错误

当我加载我的游戏时,它很难加载和“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

你的i和j循环('<'vs'<=')有些腥意,你应该在'Scanner'上使用'hasNextInt() – 2013-12-09 06:34:42

回答

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 .......