NoSuchElementException问题

时间:2012-09-30 22:14:11

标签: java exception while-loop java.util.scanner

我要做的是创建一个while循环,其中运行程序菜单直到用户输入有效的响应。

然而,我创建的扫描程序实例不想玩球,并且无论我尝试过什么,都会继续抛出NoSuchElementExceptions。

import java.util.Scanner;

public class Menu
{
    Menu()
    {
        isValid = false;
        uInput = 0;
    }

    public int mMain()
    {
        Scanner in2;

        do
        {           
            in2 = new Scanner(System.in); //For user input

            System.out.println("Please choose from the following options");
            System.out.println("1) Enter Employee Data");
            System.out.println("2) Look Up Employee Information");
            System.out.println("3) Employee Comparison");
            System.out.println("4) Quit");
            uInput = in2.nextInt(); //This is the line throwing the exception.

            if (uInput < 1 || uInput > 4)
            {
                System.out.println("Your choice was not valid, please choose another option.");
            }

            else
            {
                isValid = true;
                in2.close();
            }
        } while (!isValid);

       isValid = false; //reset for next time
       System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); //Clear screen

       return uInput;       
    }

    int uInput; //For user input
    String uInput2; //for bug fixing
    boolean isValid; //check for valid use input
}

如果需要,这是我的主要方法:

public class prg420_w4_commission_program
{
    public static void main(String[] args)
    {       
    //class references
    Processing proc = new Processing();
    Menu menu = new Menu();

    //Set up Variables
    int uInput; //For user input
    boolean uQuit = false; //set up program loop bool

    //Opening message
    System.out.println("Welcome to the Employee Data Entry Creation program.  Please follow the on-screen prompts.");
    System.out.println("");

    proc.initEDatabase(); //initialize employee database


    while (!uQuit)
    {

        uInput = menu.mMain(); //call main menu

        //Check user input
        switch (uInput)
        {
            case 1:
                proc.addEDBEntry(); //add employee entries
                break;

            case 2:
                proc.findEmployee();
                break;

            case 3:
                proc.sortEDBase();
                break;

            case 4:
                uQuit = true;
                break;

            default:
                proc.addEDBEntry();
                break;                      
        }           
    }

    System.out.println("Thank you for using the Employee Data Entry Creation program.");
  }
}

1 个答案:

答案 0 :(得分:2)

in2.close();

关闭输入流,在第一次成功扫描后,stdin关闭,每次尝试从Scanner获取任何内容都会导致NoSuchElementException被抛出。