3

I'm trying to read every character that user inputs without waiting for a "newline".

This code doesn't work, as AFAIK Scanner waits for the newline character before sending input to the application

Scanner s = new Scanner(System.in);
if(s.hasNext()){
    char c = s.next().charAt(0);
}

I also tried with BufferedReader:

System.out.println("Input something: ");
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
while(!b.ready()){
    try {
        Thread.sleep(100);
    } catch (Exception e) {
    }
}
System.out.println("Now it's ready, i'm reading the first char");
char c = (char)b.read();

But the output is:

Input something:
> abcde
Now it's ready, i'm reading the first char

So it is always waiting for the newline character.

Is there any way to read user input without waiting for newline with Java?

Thanks, any help would be appreciated

BackSlash
  • 20,445
  • 19
  • 77
  • 124

0 Answers0