扫描仪内部方法不等待答案

时间:2013-03-07 09:08:22

标签: java java.util.scanner

一直在努力解决这个问题,来回阅读讨论论坛,没有结果。任何人都可以告诉我为什么函数aMenu()的第二次调用返回零并且不等待新的用户输入?我尝试过各种各样的东西,比如hasNextInt(),nextLine(),没什么用。不应该hasNextInt()阻塞,直到用户写东西?我怎么解决这个问题?感谢。

package FirstJavaPackage;
import java.util.Scanner;

public class testScanner
{
    public static void main(String[] args)
    {
        int choice = aMenu();
        System.out.println("You typed: "+choice);
        choice = aMenu();
        System.out.println("You typed: "+choice);
    }

    public static int aMenu()
    {
        int result = 0;
        System.out.println("In aMenu... enter an int: ");
        Scanner keyboard = new Scanner(System.in);
        if (keyboard.hasNextInt())
            result = keyboard.nextInt();
        keyboard.close();
        return result;
    }
}

输出结果为:

在aMenu中......输入一个int: 2 你打字:2 在aMenu中......输入一个int: 你键入:0

3 个答案:

答案 0 :(得分:1)

您需要在对Scanner的调用中重复使用相同的aMenu()对象:

public static void main(String[] args)
{
    Scanner keyboard = new Scanner(System.in);
    int choice = aMenu(keyboard);
    System.out.println("You typed: "+choice);
    choice = aMenu(keyboard);
    System.out.println("You typed: "+choice);
}

public static int aMenu(Scanner keyboard)
{
    int result = 0;
    System.out.println("In aMenu... enter an int: ");
    result = keyboard.nextInt();
    return result;
}

有关进一步的讨论,请参阅How to use multiple Scanner objects on System.in?

答案 1 :(得分:0)

第一次通话后,您实际上关闭了System.in输入流。

来自Scanner.close()文档:

When a Scanner is closed, it will close its input source if the source 
implements the Closeable interface.

请尽量closeaMenu结束时使用您的扫描仪:在aMenu方法之外初始化扫描仪并使方法使用它。

答案 2 :(得分:0)

由于scanner.close会关闭整个输入源,因此您应该将扫描程序传递给aMenu方法并执行以下操作:

import java.util.Scanner;

public class TestScanner
{
   public static void main(String[] args)
   {
      Scanner keyboard = new Scanner(System.in);
      int choice = 0;

      do
      {
         choice = aMenu(keyboard);
         System.out.println("You typed: " + choice);
      } while (choice > 0);

      keyboard.close();
    }

    public static int aMenu(Scanner keyboard)
    {
        int result = 0;
        System.out.println("In aMenu... enter an int: ");

        if (keyboard.hasNextInt())
           result = keyboard.nextInt();

        return result;
    }
}