[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 698
  • Last Modified:

Cleaning the buffer of system.in

public class MyClass {
public static void main(String args[]){

      try{
            System.out.print("Pls enter one character and press enter");
            System.out.println(System.in.read());
            System.out.print("Pls enter another character");
            System.out.println(System.in.read());

      }catch(Exception e){
            
      }
}
}

What I received
Pls enter one character: a<--only key in here, all the result come out, seems like it buffer the enter
97
Pls enter another character: 13


What I expect
Pls enter one character: a<--key in here
97
Pls enter another character: b<--and key in here
98

What I expect
Pls enter one character: <- enter here
13
Pls enter another character: b<--and key in here
98


How to clear the buffer of system.in and read the character again?
0
william007
Asked:
william007
  • 2
2 Solutions
 
Weiping DuSenior Web DeveloperCommented:
If work in DOS, you can use skip() to skip 2 bytes. 1 is line feed and 1 is Carriage return.

try{
        System.out.print("Pls enter one character and press enter");
      System.out.println(System.in.read());
      System.in.skip(2);

      System.out.print("Pls enter another character");
      System.out.println(System.in.read());
      System.in.skip(2);

}catch(Exception e){
 
}
0
 
Weiping DuSenior Web DeveloperCommented:
System.in.skip(System.in.available());  is better and it can be used for both *nix or win
0
 
objectsCommented:
stdin is buffered, read() only returns after a CR is entered.
0
 
william007Author Commented:
Thanks:-)
0

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now