Last Updated on 27 July 2019   |   Print Email
In this article, we discuss three different ways for reading input from the user in the command line environment (also known as the “console”). Each way is fairly easy to use and also has its own advantages and drawbacks.
1. Reading User's Input using BufferedReader class
By wrapping the System.in (standard input stream) in an InputStreamReader which is wrapped in a BufferedReader, we can read input from the user in the command line. Here’s an example:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your name: ");
String name = reader.readLine();
System.out.println("Your name is: " + name);
In the above example, the readLine() method reads a line of text from the command line.Advantages: The input is buffered for efficient reading.Drawbacks: The wrapping code is hard to remember.
2. Reading User's Input using Scanner class
The main purpose of the Scanner class (available since Java 1.5) is to parse primitive types and strings using regular expressions, however it is also can be used to read input from the user in the command line. Here’s an example:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your nationality: ");
String nationality = scanner.nextLine();
System.out.print("Enter your age: ");
int age = scanner.nextInt();
Advantages:
Convenient methods for parsing primitives (nextInt(), nextFloat(), …) from the tokenized input.
The Console class was introduced in Java 1.6, and it has been becoming a preferred way for reading user’s input from the command line. In addition, it can be used for reading password-like input without echoing the characters entered by the user; the format string syntax can also be used (like System.out.printf()). Here’s an example code snippet:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
I'm trying to write a program that prompts the user to input a text file. Then ask the user for a lower-case letter to which the program will count the occurrence of the letter and also the total numbers of it's lower-case and upper-case occurrences. The program should prompt the user to "Enter name of the input file" and the program is supposed to find that text file. I've tried reading my book and searching through many tutorials to find the answer on how to create a program that can do this.
Comments
console wither the name are the same or not.