Let us see some ways to read input from console in Java −
Example
import java.util.Scanner; public class Demo{ public static void main(String args[]){ Scanner my_scan = new Scanner(System.in); String my_str = my_scan.nextLine(); System.out.println("The string is "+my_str); int my_val = my_scan.nextInt(); System.out.println("The integer is "+my_val); float my_float = my_scan.nextFloat(); System.out.println("The float value is "+my_float); } }
Output
The string is Joe The integer is 56 The float value is 78.99
A class named Demo contains the main function. An instance of the Scanner class is created and the ‘nextLine’ function is used to read every line of a string input. An integer value is defined and it is read from the standard input console using ‘nextInt’. Similarly, ‘nextFloat’ function is used to read float type input from the standard input console. They are displayed on the console.
Example
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Demo{ public static void main(String[] args) throws IOException{ BufferedReader my_reader = new BufferedReader(new InputStreamReader(System.in)); String my_name = my_reader.readLine(); System.out.println("The name is "); System.out.println(my_name); } }
Output
The name is Joe
A class named Demo contains the main function. Here, an instance of the buffered reader is created. A string type of data is defined and every line of the string is read using the ‘readLine’ function. The input is given from the standard input, and relevant message is displayed on the console.