1

For avoiding any unwanted character which has been entered in console like \n

we use nextInt() or nextLine() etc.

But in these cases actually the control is going a step ahead leaving the unwanted string or something like this. But I want to delete or flush out the memory of buffer in which other unwanted data is taken by the system. For example -->

Scanner scan=new Scanner(System.in);
scan.nextInt();
scan.nextline();//this statement will be skipped

because the system is taking \n as a line next to the integer given as input. In this case without using scan.nextLine() I want to simply clear/flush out the buffer memory where the \n was stored. Now please tell me how to delete the input buffer memory in java

Thank you. :)

ANUPAM CHANDA
  • 53
  • 2
  • 3
  • 9

1 Answers1

2

You can use this to clear all existing data in the buffer:

while(sc.hasNext()) {
    sc.next();
}

If you are only doing this to remove the newline (\n) characters from the input, you can use:

while(sc.hasNext("\n")) {
    sc.next();
}

If the goal is to only read integers and skip any other characters, this would work:

while(sc.hasNext() && !sc.hasNextInt()) {
    sc.next();
}
Pieter12345
  • 1,581
  • 1
  • 7
  • 17
  • 1
    @ANUPAMCHANDA Did this answer solve your question? If it did not, please explain your question more clear. Otherwise, mark the question as answered. – Pieter12345 Jun 22 '15 at 18:49