Reputation: 1067
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"?
Upvotes: 0
Views: 551
Reputation: 27986
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());
Upvotes: 1
Reputation: 76
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.
Upvotes: 0