1

System.in.read() is used to read a single character.

Then why does it allow the user to enter as many characters as he can until he presses enter?

Why doesn't it stop as soon as he presses a key and returns the character?

char ch = (char)System.in.read();

If the user enter "example" and then press enter, It takes the ch as e. and discards the other characters.

If there are multiple read(), it messes the whole thing.

So, why doesn't it take only the single character and then return?

Uma Kanth
  • 5,659
  • 2
  • 20
  • 41
  • 3
    It is the *terminal* that is *line oriented*. It is the *terminal* that *only gives STDIN the line when enter is pressed*. Java itself does just what it promises to do - *once* it has the data. – user2864740 Jul 08 '15 at 08:35
  • Possible duplicate: http://stackoverflow.com/questions/15307355/system-in-read-does-not-read – assylias Jul 08 '15 at 08:37
  • Useful information/links: http://stackoverflow.com/questions/1066318/how-to-read-a-single-char-from-the-console-in-java-as-the-user-types-it?rq=1 – user2864740 Jul 08 '15 at 08:37
  • Yeah what that user said. To get single key action, you have to set the terminal in raw mode and interpret key codes directly. – Chloe Jul 08 '15 at 08:37
  • perfectly what I needed. Please answer the question. – Uma Kanth Jul 08 '15 at 08:40

2 Answers2

1

System.in is of type BufferedInputStream. This type of stream caches input data until newline character is recognized. The following snippet shows you the type in the output.

System.out.println(System.in.getClass());
schrieveslaach
  • 1,689
  • 1
  • 15
  • 32
1

If there are multiple read(), it messes the whole thing.
So, why doesn't it take only the single character and then return?

To solve this issue you can wrap the standard input and read it with a Scanner instead.

For the given input:

abcd
1234

the following Scanner code will pick just the chars a and 1.

// Local vars init
char ch1 = 0, ch2 = 0;

// Wrap the stdin with scanner
Scanner s = new Scanner(System.in);

if(s.hasNextLine()) ch1 = s.nextLine().charAt(0); // reads "abcd", picks just 'a'
if(s.hasNextLine()) ch2 = s.nextLine().charAt(0); // reads "1234", picks just '1'

System.out.println(ch1 + "," + ch2); // prints a,1

// Close after use
s.close();
Ravi K Thapliyal
  • 51,095
  • 9
  • 76
  • 89