简体   繁体   English

我从System.in的输入中得到java.util.NoSuchElementException

[英]I get a java.util.NoSuchElementException on input from System.in

I am writing code for a program which displays a map based a file with x & y coordinates, as well as a type value. 我正在为程序编写代码,该程序显示具有x和y坐标以及类型值的基于文件的地图。

My code correctly displays the ASCII map and allows me to perform functions on the map, but when the code finally returns to the switch statement where it should take input for choosing the next option, it skips the line "option = input.nextInt();" 我的代码正确显示了ASCII映射,并允许我在该映射上执行功能,但是当代码最终返回到switch语句,在该语句中应接受选择下一个选项的输入时,它将跳过“ option = input.nextInt()”行;“ and continues to the finally block where "input.nextLine();" 并继续到“ input.nextLine();”的finally块 gives me a Java.util.NoSuchElementException. 给我一个Java.util.NoSuchElementException。

Does anyone know why this is? 有人知道为什么是这样吗? I know that this exception usually occurs with an enumeration when there is no such element, but I don't know why my code would skip the input.nextInt() line and then fail on input.nextLine(); 我知道,当没有这样的元素时,通常会在枚举时发生此异常,但是我不知道为什么我的代码会跳过input.nextInt()行,然后在input.nextLine()上失败;

This error occurs only when the Gorgon case is activated in the viewMap Switch case at the end. 仅当最后在viewMap Switch案例中激活了Gorgon案例时,才会发生此错误。 I have tried adding "input.nextLine()" calls before the "input.nextInt()" call, but it doesn't make a difference. 我尝试在“ input.nextInt()”调用之前添加“ input.nextLine()”调用,但这没有什么区别。

Included is the code for the Switch Statement in my MapViewer program, as well as the code for building the map and displaying it. 包括我的MapViewer程序中Switch语句的代码,以及构建地图并显示它的代码。 I have also added the Gorgon class at the end. 我还在末尾添加了Gorgon类。

public class MapViewerMenu {

    public int option = 0;
    public boolean complete = false;

    Scanner input = new Scanner(System.in);

    char [][] mapper = null;

    Map currentMap = null;
    User currentUser = null;
    Vector <Grue> currentGrues = null;

    public void run(){

        while(!complete){
            System.out.println("*******************");
            System.out.println("* Map Viewer Menu *");
            System.out.println("*******************");
            System.out.println("1. Load Files");
            System.out.println("2. Set Symbols");
            System.out.println("3. View Map");
            System.out.println("4. Scramble Map");
            System.out.println("5. Reset Map");
            System.out.println("6. Exit");
            System.out.println("");

            try{
                option = input.nextInt();
            }
            catch(Exception e){
                System.out.println("Error in input.");
                System.out.println("Try again.");
                System.out.println("");
            }
            finally{

// The Error occurs once the program exits viewMap and returns here. 
//It skips the above "option = input.nextInt();" and comes down here and fails.

                input.nextLine();
            }

            switch(option){

            //removed irrelevant cases

            case 3:
                viewMap();
                break;

            case 6:
                complete = true;
                input.close();
                break;

            }
        }
    }

    public void viewMap(){
        //removed earlier code that built part of the map for readability

        number = currentGrues.elements(); //this is an enumeration

        while(number.hasMoreElements()){
            temp3 = number.nextElement();
            int sure =2;

            switch(temp3.getName()){

            case "Gorgon":

                while(sure != 0){
                    System.out.printf("Would you like the Gorgon to change a square type?\n");
                    System.out.println("(0 for yes, 1 for no.)");

                    try{
                        sure = input.nextInt();
                    }
                    catch(Exception e){
                        System.out.println("Error in input.");
                        System.out.println("Try again.");
                        System.out.println("");
                        sure = 2;
                    }
                    finally{
                        input.nextLine();
                    }

                    if(sure == 0){
                        Gorgon gor = (Gorgon) temp3;
                        gor.boulder(currentMap, mapper);
                        after = true;
                        break;
                    }
                    else{
                        if(sure == 1){
                            break;
                        }
                    }
                }
                break;

// A boolean value after tells the program to reprint the map.

        if(after){
            System.out.println("Since some squares were changed, the updated map is printed.");
            System.out.println("");
            System.out.printf("Map Name: %s", currentMap.getName());
            System.out.println("");

            for(xpos = 0, ypos = 0; xpos < 16 && ypos < 16;){
                System.out.print(mapper[xpos][ypos]);
                xpos++;

                if(xpos < 16){
                    continue;
                }
                else{
                    System.out.println("");
                    ypos++;
                    if(ypos < 16){
                        xpos = 0;
                        continue;
                    }
                }
            }
            System.out.println("");
        }
}

//This should then go back to the "option = input.nextInt" line, where it should ask the user for input, but doesnt.

import java.util.Scanner;

public class Gorgon extends Giant {

     //Included is the function called by the viewMap switch statement.
     //I added this because the error might exist here.
     //other classes have similar functions, but perform just fine.

    public void boulder(Map map, char[][] mapper){
        int x = 0;
        int y = 0;
        Scanner input = new Scanner(System.in);

        System.out.println("The Gorgon wants to turn an adjacent Square to stone!");
        System.out.printf("Its position is (%d,%d).\n", this.currPos.col, this.currPos.row);

        do{
            do{ // Get an adjacent x coordinate
                try{
                    System.out.println("Enter an x coordinate:");
                    x = input.nextInt();
                }
                catch(Exception e){
                    System.out.println("Error in input.");
                    System.out.println("Try again:");
                    System.out.println("");
                }
                finally{
                    input.nextLine();
                }
            }while(!(x >= currPos.col-1 && x <= currPos.col+1));

            do{  // get an adjacent y coordinate
                try{
                    System.out.println("Enter a y coordinate:");
                    y = input.nextInt();
                }
                catch(Exception e){
                    System.out.println("Error in input.");
                    System.out.println("Try again:");
                    System.out.println("");
                }
                finally{
                    input.nextLine();
                }
            }while(!(y >= currPos.row-1 && y <= currPos.row+1)); // keep asking for input while the input isn't within range.

        }while(!((x >= currPos.col-1 && x <= currPos.col+1) && (y >= currPos.row-1 && y <= currPos.row+1)));

        mapper[x][y] = 'B'; //Change the value in map data.
        input.close();  //Close local input reader.

} }

The user is at (3,3) 用户位于(3,3)

I have in my collection of grues a Gorgon at (6,6) which should be able to turn an adjacent square to type "boulder", which is an obstacle the user can't stand on. 我的烟囱中有一个位于(6,6)的Gorgon,它应该能够将相邻的正方形变成“巨石”,这是用户无法站立的障碍。

Everytime I choose to use the Gorgon's function boulder, my program fails when it reaches the original switch statement at the beginning of the program. 每当我选择使用Gorgon的函数巨石时,我的程序在到达程序开头的原始switch语句时就会失败。

When the program runs, this is how is usually goes: 程序运行时,通常是这样的:

I load the appropriate files (these don't have to do with the error.) 我加载了适当的文件(这些与错误无关)。


  • Map Viewer Menu * 地图查看器菜单*


    1. Load Files 载入档案
    2. Set Symbols 设置符号
    3. View Map 查看地图
    4. Scramble Map 争夺地图
    5. Reset Map 重置地图
    6. Exit 出口

3 3

Building map... 建筑图...

The map is then displayed with ASCII characters. 然后以ASCII字符显示地图。

The user's Rope has been stolen! 用户的绳索已被盗!

Would you like the Giant to change a square type? 您想要巨人改变方形吗?

(0 for yes, 1 for no.) (0表示肯定,1表示否。)

1 1个

Meat! 肉! Meat! 肉! Meat! 肉!

Would you like the Gorgon to change a square type? 您想让Gorgon更改方形吗?

(0 for yes, 1 for no.) (0表示肯定,1表示否。)

0 0

The Gorgon wants to turn an adjacent Square to stone! Gorgon想要将相邻的Square变成石头!

Its position is (6,6). 它的位置是(6,6)。

Enter an x coordinate: 输入x坐标:

7 7

Enter ay coordinate: 输入y坐标:

6 6

Since some squares were changed, the updated map is printed. 由于某些正方形已更改,因此将打印更新的地图。

The updated is then correctly printed again. 然后,更新的文件将再次正确打印。


  • Map Viewer Menu * 地图查看器菜单*


    1. Load Files 载入档案
    2. Set Symbols 设置符号
    3. View Map 查看地图
    4. Scramble Map 争夺地图
    5. Reset Map 重置地图
    6. Exit 出口

Error in input. 输入错误。 Try again. 再试一次。

Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.util.Scanner.nextLine(Unknown Source)
    at viewer.MapViewerMenu.run(MapViewerMenu.java:92) //points to the finally block at the beginning, where "input.nextLine()" is written.
    at viewer.MapViewer.main(MapViewer.java:40) //This is just the original main that runs the program.

It fails once it returns to the class's original switch statement, but it should just return to the beginning and ask for input for the switch again. 一旦返回到该类的原始switch语句,它就会失败,但是它应该只是返回到开头,并再次要求输入该开关。

The error was fixed by going into my Gorgon's boulder function and instead of opening a new Scanner on System.in, I simply passed the existing scanner in my parameters. 该错误已通过进入我的Gorgon的boulder函数得以解决,而不是在System.in上打开新的Scanner,而只是在参数中传递了现有的扫描仪。

The fact that I created another scanner on system.in and closed it may have had something to do with my other scanner's failure. 我在system.in上创建了另一个扫描仪并关闭它的事实可能与其他扫描仪的故障有关。

Thanks to all for your help and time. 感谢大家的帮助和时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM