开发者

Why does the line keyboard = new Scanner(keyboard.nextLine()); keep the program from hanging?

I have been trying to figure out how to input multiple tokens at one time using the Scanner class. I found some code that works perfectly. I know that the Scanner.hasNext method can block indefinitely. Why does the line keyboard = new Scanner(keyboard.nextLine()); in this code keep it from doing this?

    Sc开发者_StackOverflow中文版anner 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);

Thanks!


keyboard will be a Scanner which reads tokens from the first line of input.

When you use the Scanner(String str) constructor, the resulting scanner will use str as input.

If that's clear to you, you probably just need to understand that the terminal IO is line-buffered. This means that the scanner will have nothing to read until you press return.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜