Scanner Vs BufferedReader
Jeff Odhiambo
Posted on February 15, 2022
Taking Input from User
Most of the program often request for data to be processed from the user and most of the programming language if not all provides a mechanism through which a user can enter data to be processed into the computer.
For instance in python its done through the use of input method e.g
name = input("Enter name >>> ")
In C Programming scanf is used e.g,
char name[20];
printf("[+]Enter your name >>> ");
scanf("%s",&name);
How about Java?
In Java, there are two ways of doing it.
Scanner
and BufferedReader
class are sources that serve as ways of reading inputs. When using scanner, it doesn't through an exception while when using Buffered reader it throws exceptions.
Sample code for the use of the Two
Scanner
import java.util.Scanner;
public class NameReader{
public static void main(String[] args){
int Age;
Scanner input = new Scanner(System.in);
System.out.print("[+]Enter your Age >>> ");
Age = input.nextInt();
System.out.println("Your Age is "+Age);
}
}
OutPut:
[+]Enter your Age >>> 23
Your Age is 23
Process finished with exit code 0
Buffered Reader
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class AgeReader{
public static void main(String[] args)throws Exception{
int Age;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("[+]Enter your Age >>> ");
Age = Integer.parseInt(br.readLine());
System.out.println("Hello your age is "+Age);
}
}
Output:
[+]Enter your Age >>> 23
Hello your age is 23
Process finished with exit code 0
These are the two main mechanisms through which users can interact with the computer in Java.
Posted on February 15, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.