java 在 for 循环中使用 Scanner 进行系统输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13096599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 11:28:23  来源:igfitidea点击:

Using Scanner inside a for loop for system input

javajava.util.scanner

提问by dawnoflife

I have been struggling with this for a while. I essentially want to loop through and read in as many strings as determined by num_choices. The following code only executes the else condition.

我已经为此苦苦挣扎了一段时间。我基本上想循环并读入由num_choices. 下面的代码只执行else条件。

        Scanner s2 = new Scanner(System.in);

        for(int i=0; i < this.num_choices; i++)
        {
          if(s2.hasNext())
          {

            System.out.println("Enter choice " + (i+1) +":");
            String ch = s2.next();
            //this.choices.addElement(ch);
          }
        else
        {
            System.out.println("Lets end this");

        }

    }

`

`

I am getting this: Exception in thread "main" java.util.NoSuchElementException. In the main class, this is where the error points to

我得到这个:Exception in thread "main" java.util.NoSuchElementException。在主类中,这是错误指向的地方

        choice2 = Integer.parseInt(read_choice2.next());

which is inside a while loop as well. Here is the code for that:

这也在一个 while 循环中。这是代码:

public class Main 
{
public static void main(String args[]) throws IOException
{
    Vector<Survey> mysurveys = new Vector<Survey>();
    boolean carry_on = true;
    int choice = 0;
    Scanner read_choice = new Scanner(System.in);

    System.out.println("Let's begin the Survey/Test application!");
    while(carry_on)
    {
        System.out.println("What would you like to do?");
        System.out.println("1. Create a new Survey");
        System.out.println("2. Create a new Test");
        System.out.println("3. Display a Survey");
        System.out.println("4. Display a Test");
        System.out.println("5. Save a Survey");
        System.out.println("6. Save a Test");
        System.out.println("7. Load a Survey");
        System.out.println("8. Load a Test");
        System.out.println("9. Quit");
        System.out.println();
        System.out.println("Please enter a number for the operation you want to perform: ");
        choice = Integer.parseInt(read_choice.next());
        /*try
        {
            choice = Integer.parseInt(buffer.readLine());

        }
        catch(InputMismatchException  e)
        {
            System.out.println("Invalid input. Please Enter again.");
            System.out.println();
            //read_choice.nextInt();
        }*/

        switch(choice)
        {
        case 1:
            System.out.println("Please Enter a Name for your Survey");
            String in = buffer.readLine();
            Survey s1 = new Survey();
            s1.CreateNew(in);
            mysurveys.add(s1);
            ////
            add_question(s1.type);
            break;

        case 2:
            System.out.println("Please Enter a Name for your Test");
            //String in = buffer.readLine();
            Test t1 = new Test();
            //t1.CreateNew(in);
            mysurveys.add(t1);
            break;
            ////
            //add_question(t1.type);
        case 3:


            break;
            // call Survey.display()


        case 4:


            break;


        case 5:

            Survey s = new Survey();
            ReadWriteFiles x = new ReadWriteFiles();
            x.SaveSurvey(s);
            break;


        case 6:

            Test t = new Test();
            //ReadWriteFiles x = new ReadWriteFiles();
            //x.SaveSurvey(t);
            break;


        case 7:

            carry_on = false;
            break;

        default:

            System.out.println("Incorrect Input. Try Again");
            System.out.println();
            break;
        }
    }

    read_choice.close();


}







 public static void add_question(String type) throws IOException, NullPointerException
 {
Questions q = null;
boolean carry_on2 = true;
int choice2 = 0;
Scanner read_choice2 = new Scanner(System.in);
//BufferedReader buffer2=new BufferedReader(new InputStreamReader(System.in));

while (carry_on2)
{
    //
    System.out.println("1. Add a new T/F Question");
    System.out.println("2. Add a new Multiple Choice Question");
    System.out.println("3. Add a new Short Answer Question");
    System.out.println("4. Add a new Essay Question");
    System.out.println("5. Add a new Ranking Question");
    System.out.println("6. Add a new Matching Question");
    System.out.println("7. If you want to stop adding more questions, and go back to the main menu.");
    System.out.println("Please enter a number for the operation you want to perform: ");
    choice2 = Integer.parseInt(read_choice2.next());

    /*try
    {
        choice2 = Integer.parseInt(buffer2.readLine());

    }
    catch(InputMismatchException  e)
    {
        System.out.println("Invalid input. Please Enter again.");
        System.out.println();
        //read_choice2.nextInt();
    }*/
    switch(choice2)
    {
        case 1:
            q = new TrueFalse();
            break;
        case 2:
            q = new MultipleChoice();
            break;
        case 3:
            q = new ShortAnswer();
            break;
        case 4:
            q = new Essay();
            break;
        case 5:
            q = new Ranking();
            break;
        case 6:
            q = new Matching();
            break;
        case 7:
            carry_on2 = false;
            break;
        default:
            System.out.println("Incorrect Input.");
            break;

    }
    q.createQuestion(type);

}
}
}

I realize there is a lot of messy code, and I apologize for that. I just wanted to show the entire thing, so it's easier to spot the problem. Help would be appreciated.

我意识到有很多乱七八糟的代码,对此我深表歉意。我只是想展示整个事情,这样更容易发现问题。帮助将不胜感激。

回答by hqt

In general way, you should add if(read_choice.hasNext())before invoking read_choice.next();You have the exception java.util.NoSuchElementExceptionbecause no elements found to be read. this is a good habit.

一般来说,您应该if(read_choice.hasNext())在调用之前添加read_choice.next();您有异常,java.util.NoSuchElementException因为没有找到要读取的元素。这是一个好习惯。

About your problem, you are getting error because you has closed scanner before finish reading. Put read_choice.close()outside of loop.

关于您的问题,您收到错误消息,因为您在完成阅读之前关闭了扫描仪。放在read_choice.close()循环之外。

Moreover, for simplify, if you want to read integer, just simple : scanner.nextInt().

此外,为了简化,如果您想读取整数,只需简单 : scanner.nextInt()

回答by Bhesh Gurung

read_choice.close(); 

Don't close the scanner as long as you are not done reading all the inputs. Doing also closes the underlying input stream (System.in), check the documention;

只要您没有读完所有输入,就不要关闭扫描仪。这样做也会关闭底层输入流(System.in),检查文档

You don't need to initialize the Scannermultiple times. Just create one instance and pass it around (keep using it).

您不需要Scanner多次初始化。只需创建一个实例并传递它(继续使用它)。

Also,

还,

for(int i=0; i < this.num_choices; i++)
{
   //if(s2.hasNext())
   //{

       System.out.println("Enter choice " + (i+1) +":");
       String ch = s2.next();
       //this.choices.addElement(ch);

you don't need that condition check. The next()will block until the input is entered.

你不需要那个条件检查。在next()将阻塞,直到输入的输入。