当前位置: 首页 > 知识库问答 >
问题:

try/catch块中带有扫描程序的NoSuchElementException

凌啸
2023-03-14
package game;

import world.Maze;

public class MainProgram {

    public static void main(String[] args) {

        // Initialize objects concerned with playing the game
        Player myPlayer = new Player();
        Maze myMaze = new Maze();

        // Print welcome message and ask the player for his/her name
        System.out.println("Hi there! Welcome to this maze game in Java by MV. \n");
        myPlayer.setPlayerNameWithScanner();

        // Ask the player which game mode he/she would like to play: single player or multiplayer?
        int choice = MenuParser.startUpMenu();
        System.out.println(choice);
        // Parse input and depending on the answer initialize the corresponding menu to start the game
    }

}
package game;

import java.util.InputMismatchException;
import java.util.Scanner;

public class MenuParser {

    public static void pause() {

        System.out.println("Please hit enter to continue.");
        Scanner hitEnter = new Scanner(System.in);
        hitEnter.nextLine();
        hitEnter.close();
    }

    public static int startUpMenu() {

        int choice = 0;

        System.out.println("Which game mode would you like to play?" + "\n");
        System.out.println("\t 1. Single player.");
        System.out.println("\t 2. Robot.");

        try(Scanner startUp = new Scanner(System.in)){

            choice = startUp.nextInt();
            System.out.println(choice);

            if(choice != 1 || choice != 2) {

                System.out.println("Sorry, this is not a valid choice.");
                startUpMenu();
            }
        }
        catch(InputMismatchException im) {

            System.out.println("Sorry, it seems the input is of wrong type.");
            startUpMenu();
        }
        return choice;
    }
}

Player类如下所示:

package game;

import java.util.InputMismatchException;
import java.util.Scanner;

public class Player {

    private String playerName;
    private int playerStepScore;

    public Player () {
    }

    public void setPlayerNameWithScanner(){

        System.out.println("Please enter your name. \n");

        try(Scanner playerNameScanner = new Scanner(System.in);){

            String playerName = playerNameScanner.nextLine();
            setPlayerName(playerName);
        }
        catch(InputMismatchException im) {
            System.out.println("Input seems to be wrong");
            setPlayerNameWithScanner();
        }
    }

    public String getPlayerName() {
        return playerName;
    }
    public void setPlayerName(String playerName) {
        this.playerName = playerName;
    }
    public int getPlayerStepScore() {
        return playerStepScore;
    }
    public void setPlayerStepScore(int playerStepScore) {
        this.playerStepScore = playerStepScore;
    }


}

前面的main方法(它使用多个扫描器,包括try-with-recours,没有任何错误或异常)如下所示:

package game;

import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.FileReader;
import game.Cell;
import game.Maze;
import game.Border;

public class Program {

    public static void main(String[] args) {

        /*
         * General variables that will be used throughout the loops
         * that follow; maxXCoor and maxYCoor are used as maximum values
         * to initialize a grid of a certain size; myMaze is a Maze object
         * which is needed to access its methods throughout the loops.
         */
        int maxXCoor = 0;
        int maxYCoor = 0;
        Maze myMaze = new Maze();

        /*
         * A Scanner is invoked to simply deal with the entry
         * of the file name; this location is then saved in the
         * variable fileName, which is then passed onto the next
         * Scanner and FileReader.
         */
        System.out.println("Please enter a file name");
        Scanner scan = new Scanner(System.in);
        String fileName = scan.nextLine();
        scan.close();
        System.out.println(fileName);

        /*
         * This first block is used to scan the entire input file
         * and look for maxXCoor and maxYCoor to initialize the grid.
         */
        try(Scanner input = new Scanner(new FileReader(fileName));){

            int count = 1;
            while(input.hasNextLine()) {

                /*
                 * Every line is read as a String which is then 
                 * split using a comma as the delimiter. Every
                 * part that is delimited by a comma is then put into an
                 * array called words.
                 */
                String line = input.nextLine();
                String[] words = line.split(",");

                /*
                 * Basic sanity check to make sure the input file uses
                 * the template which was agreed upon, where the first line
                 * are just headers.
                 */
                if(count == 1) {

                    if(!(words[0].toLowerCase()).equals("xcoordinate")) {

                        System.out.println("It looks like there is an issue with the template of your input file.");
                        System.out.println("Please check your input file and try again!");
                        System.exit(0);
                    }
                }
                /*
                 * Once we're not at line one anymore, we can start checking
                 * the current coordinates, xCoor and yCoor, against
                 * the maximum coordinates, maxXCoor and maxYCoor.
                 */
                else {

                    int xCoor = Integer.parseInt(words[0]);
                    int yCoor = Integer.parseInt(words[1]);

                    if(xCoor > maxXCoor) {

                        maxXCoor = xCoor;
                    }
                    if(yCoor > maxYCoor) {

                        maxYCoor = yCoor;
                    }
                }
                count++;
            }
        }
        catch(FileNotFoundException fe) {
            System.out.println("File not found");
            System.exit(0);
        }

        /*
         * As Java uses zero-indexing, we will want to
         * augment the values of our maximum coordinates
         * by one, to avoid IndexOutOfBoundsExceptions in
         * the future. After that we initialize a 2D array
         * of type Cell with these coordinates.
         */
        maxXCoor++;
        maxYCoor++;
        Cell[][] myGrid = new Cell[maxXCoor][maxYCoor];


        try(Scanner input = new Scanner(new FileReader(fileName));){

            int count = 1;
            while(input.hasNextLine()) {

                String line = input.nextLine();
                String[] words = line.split(",");

                if(count > 1) {

                    int xCoor = Integer.parseInt(words[0]);
                    int yCoor = Integer.parseInt(words[1]);
                    Border borderNorth = new Border(words[2]);
                    Border borderSouth = new Border(words[3]);
                    Border borderEast = new Border(words[4]);
                    Border borderWest = new Border(words[5]);
                    Cell myCell = new Cell(borderNorth,borderSouth,borderEast,borderWest);
                    myGrid[xCoor][yCoor] = myCell;

                }
                count++;
            }
        }
        catch(FileNotFoundException fe) {
            System.out.println("File not found");
            System.exit(0);
        }

        for(int x = maxXCoor-1; x >= 0; x--) {
            // Draw north & south wall
            for(int y = 0; y < maxYCoor; y++) {
                Border myBorderNorth = myGrid[x][y].getNorthWall();
                String myTypeNorth = myBorderNorth.getType();
                if(myTypeNorth.equals("wall")) {
                    System.out.print("+---");
                }
                else {
                    System.out.print("+   ");
                }
                if(y == maxYCoor-1) {
                    System.out.println("+");
                }
            }
            // Draw west & east wall
            for(int y = 0; y < maxYCoor; y++) {
                Border myBorderWest = myGrid[x][y].getWestWall();
                String myTypeWest = myBorderWest.getType();
                if(myTypeWest.equals("wall")) {
                    System.out.print("|   ");
                }
                else {
                    System.out.print("    ");
                }
                // Draw last eastern wall
                if(y == maxYCoor-1) {
                    System.out.println("|");                    
                }
            }
            // Draw last southern wall
            if(x == 0) {
                for(int y = 0; y < maxYCoor; y++) {
                    System.out.print("+---");
                }
                System.out.println("+");
            }
        }
        myMaze.setGrid(myGrid);
    }

}

共有1个答案

卫深
2023-03-14

您有以下代码:

        try(Scanner startUp = new Scanner(System.in)){
            //stuff
        }

这被称为使用资源的尝试。当这个try块执行完毕时,代码将自动关闭扫描器。

但是,一旦关闭了与System.in关联的扫描程序,则System.in将保持关闭状态。如果尝试读取其他内容,即使使用新的扫描程序,也会得到NoSuchelementException。这似乎就是这里正在发生的事情。很可能是SetPlayerNameWithScanner以类似的方式关闭扫描程序,导致您的问题。

 类似资料:
  • 问题内容: 我正在审查一些新代码。该程序仅具有try和finally块。由于不包含catch块,如果try块遇到异常或任何可抛出的异常,它将如何工作?它是否直接进入了finally块? 问题答案: 如果try块中的任何代码都可以引发已检查的异常,则它必须出现在方法签名的throws子句中。如果引发了未经检查的异常,则该异常会冒泡退出方法。 无论是否引发异常,都始终执行finally块。

  • 问题内容: 我最初从大学开始编程,然后学习了vb.net。现在,我决定转向Java并进行一些查询。在vb中,try catch语句的布局如下 但是在Java网站(https://docs.oracle.com/javase/tutorial/essential/exceptions/putItTogether.html)中,我发现在Java中,您使用了两个陷阱,如下所示: 我希望有人能够解释为什么

  • 我写了一个小猜谜游戏,你必须猜一个随机数。我完成了这个程序,但我想做的最后一件事是:当用户应该输入一个数字及其和InputMissmatching错误或其他错误时,系统告诉他他必须输入一个大于0的数字。但在这个do-while循环之后,扫描仪的变量不再工作!如何设置try/catch/finally循环,以仅获取整数,而不是整数或0时不崩溃? 问题是guessNumber和numberOfUser

  • 问题是,如果我输入一个正数(所以一切都正确),我必须输入它两次!同样,当我输入一个负数时,我需要输入两次。当我输入一个字符串时,我会得到一个“错误”,所以我想这还算不错。它是这样显示的: Bitte geben Sie die kleinste阳性Zahl des Intervalls Ein:-2 -3 -7 Bitte Geben Sie eine阳性Zahl ein 2

  • 本文向大家介绍说明PowerShell中的Try / Catch / Finally块,包括了说明PowerShell中的Try / Catch / Finally块的使用技巧和注意事项,需要的朋友参考一下 PowerShell中的Try / Catch块用于处理脚本中产生的错误。具体而言,错误应该是终止错误。在最后在PowerShell中块不是强制性的,每次沿写try / catch语句,但它会