is there a NEED for FLUSHING THE BUFFER ?

Is there any need 2 clear the buufer in Java in problems of codechef ?
Like the code in Java

import java.io.*;
import java.util.Scanner;
public class CodeChef {

public static void main(String[] args) {
  
       Scanner sc= new Scanner(System.in);
       String str ;
       str=sc.nextLine();
sc.nextLine();                   // Is this Line Required ???  'Flushing the Buffer'

       long a;
       a=sc.nextLong();
sc.nextLine();                   // Is this Line Required ???   ' Flushing the Buffer'
       double b;
       b=sc.nextDouble();
      
       System.out.println(ch);
  

}

}

Lets see this piece of code:

long a;
a=sc.nextLong();
sc.nextLine();  

Your method nextLong() will only read the long value and then stop. So, when you enter a value (long, int, double) and hit ‘Enter’, a new-line character \n is also added to your buffer. Your nextLong() method reads the long value and stops, leaving behind the \n in the buffer. So, to fix this, sc.nextLine() is added which will read the buffer and throw away whatever is left in the buffer.

Although, in your first case, see below code:

str=sc.nextLine();
sc.nextLine();  

I don’t think the line sc.nextLine(); is needed, in this case.

1 Like