0

I wanted to extract input from my scanner and insert it directly into a typesafe arraylist. Here is my code:

public static void main(String args[])
{
    List<Integer> arglist=new ArrayList<Integer>();
    List<Integer> resultlist=new ArrayList<Integer>();
    Scanner in=new Scanner(System.in);
    System.out.println("Scanning");
    while(in.hasNext())
    {
        arglist.add(in.nextInt());
    }
    System.out.println("Scan complete, sorting...");
    System.out.println(arglist);
    resultlist=qksort(arglist);
    System.out.println(resultlist);

}

This works only when I explicitly terminate input using Ctrl+Z. Shouldn't the stream terminate when I press "Enter"?

1
  • 1
    No with System.in. It will work with a file as input, but with System.in you will only have the EOF flag set when you hit Ctrl + Z. Your while body will run any time you press Enter, for every word in the line, but the hasNext method will wait for the OS return again, so, unless you terminate the console input, it will wait forever. Commented Sep 22, 2015 at 10:41

2 Answers 2

1

No it won't terminate when you press the enter key. The scanner will read that as a newline character and interpret it as a delimiter between tokens and happily continue.

A very simple solution if you want to continue processing is:

while (in.hasNextInt()) {
    argList.add(in.nextInt());
}

That way the first time you type something that isn't a number or whitespace (e.g. "exit") it will continue.

If you particularly want to just input a single line then you can use the scanner to read a line and then scan that line:

Scanner scanner = new Scanner(System.in);
scanner = new Scanner(scanner.nextLine());
Sign up to request clarification or add additional context in comments.

4 Comments

"The scanner will read that as a newline character and happily continue." To be more precise ... it ignores the newline character. Like hasNextInt.
@Tom it will still consider it a delimiter for the purpose of defining a token right? I'm not sure what you mean by ignoring it - isn't it treated like any other whitespace?
@Tom I realised it was a bit ambiguous so tried to make it clearer in my answer.
Yes, that is better. next() doesn't care about whitespace and doesn't read them. It waits for valid tokens. nextLine() on the other hand handles new line characters.
0

If End of Stream didn't appear as in case of Files or 'Ctrl + Z' in case of standard input, then hasNext() method is blocking...it means-
Either it finds pattern in buffer: in this case it return True.
Or if it goes for reading from underline stream: in this case it might block.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.