2013-03-07 46 views
3

一直在挣扎着这一天,来回阅读论坛,没有结果。任何人都可以告诉我为什么函数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 在AMENU ...进入一个int: 您键入: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?

+0

感谢所有,现在它工作正常,但我还是不明白的逻辑完全。好的,我在aMenu()函数结束时关闭了输入流,但是不是我在下一次调用时再次打开它,并且扫描仪键盘=新扫描仪(System.in)?我就是这么做的,我已经阅读过你推荐的链接,但我想我仍然错过了一些东西。为什么不这样工作,以后关闭并重新打开流?再次感谢您在这里建立一个伟大的社区! – 2013-03-07 09:40:39

+1

@xx:首先,当你调用'keyboard.close()'时,它也会关闭'System.in'。从那时起,无论您是否尝试创建更多扫描仪,都无法从System.in中读取任何内容。 – NPE 2013-03-07 09:42:37

+0

谢谢,现在我明白了。所以,一旦一个流被关闭,它仍然是关闭的程序的其余部分,你不能扫描不存在的东西.. – 2013-03-07 10:02:21

0

第一次调用后,您实际关闭System.in输入流。

Scanner.close()文档:

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

尽量不要在aMenu年底close扫描仪:初始化aMenu方法外扫描仪,使该方法使用它。

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; 
    } 
}