How to stop reading multiple lines from stdin using Scanner?

与世无争的帅哥 提交于 2019-12-03 06:59:31

You could try asking for empty inputs

import java.util.Scanner;

public class Test
{
    public static void main(String[] args)
    {   
        String line;
        Scanner stdin = new Scanner(System.in);
        while(stdin.hasNextLine() && !( line = stdin.nextLine() ).equals( "" ))
        {
            String[] tokens = line.split(" ");
            System.out.println(Integer.parseInt(tokens[1]));
        }
        stdin.close();
    }
}
  • Your code is almost completed. All that you have to do is to exit the while loop. In this code sample I added a condition to it that first sets the read input value to line and secondly checks the returned String if it is empty; if so the second condition of the while loop returns false and let it stop.
  • The array index out of bounds exception you will only get when you're not entering a minimum of two values, delimitted by whitespace. If you wouldn't try to get the second value >token[1]< by a static index you could avoid this error.
  • When you're using readers, keep in mind to close after using them.
  • Last but not least - have you tried the usual Ctrl+C hotkey to terminate processes in consoles?

Good luck!

You could also put your values in a file e.g. input.txt and do:

java Test < input.txt
Mike Samuel

From the shell, hit Ctrl-D and it will close stdin. Alternatively, pipe input in

cat your-input-file | java Test

To stop the input, you could either prompt the user to enter quit to exit, and then test for the presence of that String in the input, exiting the loop when found, or you could use a counter in the loop, exiting the loop when the maximum iterations have been reached. The break statement will get you out of the loop.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!