Created
March 20, 2019 16:10
-
-
Save neotam/fde8532bbc02b683a3bcbbfc3f07c072 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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