如何在 Java 中获取用户输入? [英] How to get the user input in Java?
本文介绍了如何在 Java 中获取用户输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试创建一个计算器,但我无法让它工作,因为我不知道如何获取用户输入.
I attempted to create a calculator, but I can not get it to work because I don't know how to get user input.
如何在 Java 中获取用户输入?
How can I get the user input in Java?
推荐答案
您可以根据需要使用以下任一选项.
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();
BufferedReader
和 InputStreamReader
类
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.
这篇关于如何在 Java 中获取用户输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文