This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

Question: How do YOU get user input in Java?

I tried to create a calculator, but couldn’t get it to work because I didn’t know how to get user input. How do you get user input in Java?

Answer 1:

You can use any of the following options on request.

1, the Scanner class

import java.util.Scanner; 
/ /...
Scanner scan = new Scanner(System.in);
String s = scan.next();
int i = scan.nextInt();
Copy the code

BufferedReader and InputStreamReader classes

import java.io.BufferedReader;
import java.io.InputStreamReader;
/ /...
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
int i = Integer.parseInt(s);
Copy the code

3, a DataInputStream class

import java.io.DataInputStream;
/ /...
DataInputStream dis = new DataInputStream(System.in);
int i = dis.readInt();
Copy the code

In particular, the readLine method DataInputStream in the class is deprecated. To get the String value, use the previous solution with BufferedReader

4, the Console class

import java.io.Console;
/ /...
Console console = System.console();
String s = console.readLine();
int i = Integer.parseInt(console.readLine());
Copy the code

In some ides, the above approach does not work well

The most widely used method is Scanner, which I personally prefer because of its simplicity and power to parse text into raw data.

Advantages of using Scanner:

1. The Scanner class is easy to use

2, easy to handle various types of numeric data (int, short, byte, float, long and double)

3. It is definitely more convenient to ignore checking for exceptions in the program. Programmers need to discipline and make their programs more elegant by specifying and catching exceptions.

4. Tags that can read lines, Spaces, and regular expression delimiters

So if you enter a lot of numbers, the Scanner automatically parses them, which is handy