Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
// write your code here
System.out.println("Java Console Input Demo");
readUsingScanner();
System.out.print("\n ============= * ==============\n");
readUsingBufferedReader();
System.out.print("\n============= * ============== \n");
readUsingConsole();
}
private static void readUsingScanner(){
System.out.println("Reading inputs using java.util.Scanner");
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine();
System.out.print("Enter your age: ");
int age = sc.nextInt();
System.out.printf("You Entered Name: %s Age: %d ", name, age);
}
private static void readUsingBufferedReader() throws IOException {
System.out.println("Reading inputs using java.io.BufferedReader");
InputStreamReader sr = new InputStreamReader(System.in);
BufferedReader bf = new BufferedReader(sr);
System.out.print("Enter your name: ");
String name = bf.readLine();
System.out.print("Enter your age: ");
String ageString = bf.readLine();
StringTokenizer st = new StringTokenizer(ageString);
int age = Integer.parseInt(st.nextToken());
System.out.printf("You Entered Name: %s Age: %d", name, age);
}
private static void readUsingConsole(){
System.out.println("Reading inputs using System.Console");
Console console = System.console();
if (console == null){
System.out.println("No Console Available to read input");
System.exit(0);
}
String name = console.readLine("Enter Your name: ");
char[] pw = console.readPassword("Hello %s. Please enter password: ", name);
System.out.printf("Entered name: %s secred: %s", name, String.valueOf(pw));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.