Summary of common methods of receiving keyboard input in java

1. java.util.Scanner:

Scanner sc=new Scanner(System.in);

int n=sc.nextInt();//Receive Integer

String str=sc.next();//Receive String, do not accept spaces or tab keys

String str=sc.nextLine();//Receive String, accept space or tab key, end with enter key

while(sc.hasNextLine()){//

    String str=sc.nextLine();

}

2. java.io.BufferedReader 和 java.io.InputStreamReader:

BufferReader br=new BufferReader(new InputStreamReader(System.in));

String str=br.readLine();//Read a line, this method is more efficient

String [] str_arr=str.split(" ");// Divide a line of string into a string array with spaces as the boundary


Pay attention to read and write exceptions:

throw IOException:

The exception object that is thrown manually when an abnormal situation is encountered when the program is running, informs that the internal operation of the method encounters an abnormal situation.

throws IOException:

It is a declaration of the exception to be thrown inside the method, which informs the caller of the method of the exception that this method may throw, so that the caller can use the try{}catch{} method body to catch the exception for easy processing.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324617818&siteId=291194637