且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Java 中获取用户输入?

更新时间:2023-01-11 21:05:58

您可以根据需要使用以下任一选项.

You can use any of the following options based on the requirements.

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


BufferedReaderInputStreamReader

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);


DataInputStream一个>类

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

DataInputStream 类中的 readLine 方法已被弃用.要获取字符串值,您应该使用先前的解决方案与 BufferedReader

The readLine method from the DataInputStream class has been deprecated. To get String value, you should use the previous solution with BufferedReader

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

显然,这种方法在某些 IDE 中效果不佳.

Apparently, this method does not work well in some IDEs.