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
  • 53
  • 2
  • 3
  • 11

2 Answers2

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,713
  • 1
  • 11
  • 18
  • 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
0

you can simply use one more scan.nextLine() before taking the string as input.

Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
scan.nextLine();  // clears the input buffer
String s = scan.nextLine();  // this statement won't get skip

Reference : the solution to this hackerrank question uses the same idea which I provided

nakhodkin
  • 1,327
  • 1
  • 17
  • 27