Java: keyboard input

Caporegime
Joined
16 May 2003
Posts
25,367
Location
::1
Playing with a piece of Java which reads this from the console:
Code:
475.6
11.9 27.4 14.98 6
102.0 99.9
220.0 132.9
256.3 147.9
275.0 102.9
277.6 112.9
381.8 100.9
516.3
15.7 22.1 20.87 3
125.4 125.9
297.9 112.9
345.2 99.9
-1

Normally, I'd have used a BufferedReader and recursed through each line with calls to readLine(), but it falls down on the last line because there's no carriage return after "-1".

Is there a better way that I'm missing?
 
Yes use Scanner class and .hasNext(), better detection of eof's and tokenization.
 
Last edited:
So if I use, say:
Code:
import java.util.Scanner;
import java.util.ArrayList;

public class KeyboardTest
{

	public static void main(String[] args)
	{
		try
		{
			Scanner sc = new Scanner(System.in);
			String line = sc.next();
			while (!line.equals("-1"))
			{
				line = sc.next();
			}
		} catch (Exception e)
		{
			System.out.println(e);
		}
	}
}

As soon as I type "-1", it should immediately terminate, without needing a carriage return at the end?
 
As soon as I type "-1", it should immediately terminate, without needing a carriage return at the end?

No because your using System.in as your InputStream which suspends the executing thread until you send a carriage return (by pressing enter). If you was using something like a file as the InputStream then yes it would terminate when it hits "-1".
 
Back
Top Bottom