How to stop reading multiple lines from stdin using Scanner?

后端 未结 4 1896
暗喜
暗喜 2021-02-06 05:28

I\'m working on an JAVA assignment should process multiple lines of input. The instructions read \"Input is read from stdin.\"

An example of sample input is given:

4条回答
  •  死守一世寂寞
    2021-02-06 05:38

    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!

提交回复
热议问题