2011-09-15 17 views
3

我一直在试图弄清楚如何使用Scanner类一次输入多个标记。我发现一些完美的代码。我知道Scanner.hasNext方法可以无限期阻止。为什么在这段代码中的行keyboard = new Scanner(keyboard.nextLine());阻止它这样做?为什么线键盘=新扫描仪(keyboard.nextLine());保持程序挂起?

Scanner keyboard = new Scanner(System.in); 
    LinkedList<String> ll = new LinkedList<String>(); 

    System.out.println("Please enter your full name: "); 
    keyboard = new Scanner(keyboard.nextLine()); 

    while(keyboard.hasNext()) 
    { 
     System.out.println("tag "); 
     ll.add(keyboard.next()); 

    } 

    System.out.println(ll); 

谢谢!

回答

5

keyboard将是从第一行输入读取标记的Scanner

当您使用Scanner(String str)构造函数时,生成的扫描程序将使用str作为输入。

如果这很清楚,您可能只需要了解终端IO是线路缓冲的。这意味着扫描仪在您按返回之前没有任何可读的内容。