加载/保存GUI游戏--NoSuchElementException错误



我对在Java中使用GUI和JPanel非常陌生。现在我正在开发一款可以保存和加载的游戏。保存时,它使用一个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()==#)处。我已经确定在文件中还有一个整数。

您应该正确保存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 .......

最新更新