Three ways to receive keyboard input in Java

  • 2020-04-01 03:54:16
  • OfStack


import java.io.BufferedReader;  
import java.io.IOException;  
import java.io.InputStreamReader;  
import java.util.Scanner;  
 
public class EnterTest { 
   
  public static void main(String[] args) { //The main method
    CharTest();  //Call the system.in method
    ReadTest();  //Call the ReadTest method
    ScannerTest();//Call the ScannerTest method
  } 
   
  public static void CharTest(){  
    try{ 
      System.out.print("Enter a Char:"); 
      char i = (char)System.in.read(); 
      System.out.println("Yout Enter Char is:" + i); 
    } 
    catch(IOException e){ 
      e.printStackTrace(); 
    } 
     
  } 
   
  public static void ReadTest(){ 
    System.out.println("ReadTest, Please Enter Data:"); 
    InputStreamReader is = new InputStreamReader(System.in); //New constructs the InputStreamReader object
    BufferedReader br = new BufferedReader(is); //Pass the constructed method to the BufferedReader
    try{ //There is one IOExcepiton in this method that needs to be captured
      String name = br.readLine(); 
      System.out.println("ReadTest Output:" + name); 
    } 
    catch(IOException e){ 
      e.printStackTrace(); 
    } 
     
  } 
   
  public static void ScannerTest(){ 
    Scanner sc = new Scanner(System.in); 
    System.out.println("ScannerTest, Please Enter Name:"); 
    String name = sc.nextLine();  //Reads the string input
    System.out.println("ScannerTest, Please Enter Age:"); 
    int age = sc.nextInt();    //Read the integer input
    System.out.println("ScannerTest, Please Enter Salary:"); 
    float salary = sc.nextFloat(); //Read the float type input
    System.out.println("Your Information is as below:"); 
    System.out.println("Name:" + name +"n" + "Age:"+age + "n"+"Salary:"+salary); 
  } 
} 

Conclusion:
To get input from the keyboard:
Python provides, python2 has raw_input(), python3 has input().
C provides the scanf() function
C++ provides cin() to get keyboard input
There is no ready-made function in Java to get keyboard input, but it can still be implemented using the above methods, of which method 3 should be the simplest and most convenient.


Related articles: