Scanner and BufferedReader:
Scanner and BufferedReader are used to get input from user using STD INPUT.
The syntax and examples are given below, I will explain the concept in my upcoming post.
Scanner syntax :
Scanner sc = new Scanner(System.in);
BufferedReader syntax :
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Program to Understand Scanner and BufferedReader:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class inputoutput {
public static void main(String[] args) {
scannerInput();
bufferedSample();
}
public static void bufferedSample() {
System.out.println(":::Example for BufferedReader:::");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.println("Enter your Name: ");
String name = br.readLine();
System.out.println("Enter your Age :");
int age = Integer.parseInt(br.readLine());
System.out.println("Enter your Sex :");
char sex = (char) br.read();
System.out.println("Name: " + name + "\n" + "Age: " + age + "\n" + "Sex: " + sex);
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void scannerInput() {
System.out.println(":::::Example with Scanner::::");
Scanner sc = new Scanner(System.in);
System.out.println("Enter a Name:");
String name = sc.next();
System.out.println("Enter an Age: ");
int age = sc.nextInt();
System.out.println("Enter the Sex: ");
char sex = sc.next().charAt(0);
System.out.println("Name :" + name);
System.out.println("Age :" + age);
System.out.println("Sex :" + sex);
}
}