When using Buffered reader we need to import java.io package so we need to handle exception either by try and catch or by using throws Exception. There is one disadvantage of using Scanner class when we use nextLine after nextInt:
it does not read values and the output is different from the expected output
//example scanner
import java.util.Scanner;
public class c
{
public static void main(String args[])
{
Scanner scn = new Scanner(System.in);
System.out.println("Enter an integer");
int a = scn.nextInt();
System.out.println("Enter a String");
String b = scn.nextLine();
System.out.printf("You have entered:- "+ a + " " + "and name as " + b);
}
}
Input: 2,rajat
Expected output: You have entered:-2 and name as rajat
Actual output: You have entered:-2 and name as
It does not take rajat in string b whereas there is no such problem with BufferReader class
//example Buffered Reader
import java.io.*;
class c
{
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter an integer");
int a = Integer.parseInt(br.readLine());
System.out.println("Enter a String");
String b = br.readLine();
System.out.printf("You have entered:- " + a + " and name as " + b);
}
}
Input 2,rajat
Expected output: You have entered:-2 and name as rajat
Actual output: You have entered:-2 and name as rajat