In Java, there are four different ways to read user input in the middle of the command line (console).
1.Using Buffered Reader Class
This is the classic Java method for accepting input that was introduced in JDK1.0. This method is used by wrapping System.in (standard input stream) in an InputStreamReader, which is wrapped in a BufferedReader. We can read the data entered by the user on the command line.
Implementation:
Java
// Java program to demonstrate BufferedReader import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Test { public static void main(String[] args) throws IOException { // Enter data using BufferReader BufferedReader reader = new BufferedReader( new InputStreamReader(System.in)); // Reading data using readLine String name = reader.readLine(); // Printing the read line System.out.println(name); } }
Input:
Geek
Output:
Geek
Note: To read other types, we use functions like Integer.parseInt(), Double.parseDouble(). To read multiple values, we use split().
2. Using Scanner Class
This is presumably the most favored strategy to take input. The primary motivation behind the Scanner class is to parse crude sorts and strings utilizing normal articulations, in any case, it is likewise can be utilized to peruse contribution from the client in the order line.
To see more differences, please see this article.
// Java program to demonstrate working of Scanner in Java import java.util.Scanner; class GetInputFromUser { public static void main(String args[]) { // Using Scanner for Getting Input from User Scanner in = new Scanner(System.in); String s = in.nextLine(); System.out.println("You entered string " + s); int a = in.nextInt(); System.out.println("You entered integer " + a); float b = in.nextFloat(); System.out.println("You entered float " + b); // closing scanner in.close(); } }
Input:
GeeksforGeeks 12 3.4
Output:
You entered string GeeksforGeeks You entered integer 12 You entered float 3.4
3. Using Command line argument
Most utilized client contribution for serious coding. The order line contentions are put away in the String design. The parseInt strategy for the Integer class changes over string contention into Integer. Likewise, for buoy and others during execution. The utilization of args[] appears in this info structure. The death of data happens during the program run. The order line is given to args[]. These projects must be run on cmd.
Code:
JAVA
// Program to check for command line arguments class Hello { public static void main(String[] args) { // check if length of args array is // greater than 0 if (args.length > 0) { System.out.println( "The command line arguments are:"); // iterating the args array and printing // the command line arguments for (String val : args) System.out.println(val); } else System.out.println("No command line " + "arguments found."); } }
Command Line Arguments:
javac GFG1.java java Main Hello World
Output:
The command line arguments are: Hello World