我试图创建一个计算器,但我不能让它工作,因为我不知道如何获得用户输入。
如何在Java中获得用户输入?
我试图创建一个计算器,但我不能让它工作,因为我不知道如何获得用户输入。
如何在Java中获得用户输入?
当前回答
最好的两个选项是BufferedReader和Scanner。
使用最广泛的方法是Scanner,我个人更喜欢它,因为它的简单性和易于实现,以及它将文本解析为原始数据的强大实用程序。
使用扫描仪的优点
易于使用的Scanner类 轻松输入数字(int, short, byte, float, long和double) 异常是未检查的,这更方便。这取决于程序员的文明,并指定或捕获异常。 是否能够读取行、空格和正则表达式分隔的令牌
BufferedInputStream的优点
BufferedInputStream是关于读取数据块,而不是一次读取一个字节 可以读取字符,字符数组和行吗 抛出检查过的异常 快速的性能 同步(你不能在线程间共享扫描器)
总的来说,每种输入法都有不同的目的。
如果你输入大量的数据BufferedReader可能 对你更好 如果你输入大量的数字,扫描仪做自动解析 这很方便
对于更基本的用途,我建议使用Scanner,因为它更容易使用,也更容易编写程序。下面是一个快速创建扫描器的示例。下面我将提供一个关于如何使用Scanner的全面示例
Scanner scanner = new Scanner (System.in); // create scanner
System.out.print("Enter your name"); // prompt user
name = scanner.next(); // get user input
(有关BufferedReader的更多信息,请参阅如何使用BufferedReader,并参阅读取字符行)
java.util.Scanner
import java.util.InputMismatchException; // import the exception catching class
import java.util.Scanner; // import the scanner class
public class RunScanner {
// main method which will run your program
public static void main(String args[]) {
// create your new scanner
// Note: since scanner is opened to "System.in" closing it will close "System.in".
// Do not close scanner until you no longer want to use it at all.
Scanner scanner = new Scanner(System.in);
// PROMPT THE USER
// Note: when using scanner it is recommended to prompt the user with "System.out.print" or "System.out.println"
System.out.println("Please enter a number");
// use "try" to catch invalid inputs
try {
// get integer with "nextInt()"
int n = scanner.nextInt();
System.out.println("Please enter a decimal"); // PROMPT
// get decimal with "nextFloat()"
float f = scanner.nextFloat();
System.out.println("Please enter a word"); // PROMPT
// get single word with "next()"
String s = scanner.next();
// ---- Note: Scanner.nextInt() does not consume a nextLine character /n
// ---- In order to read a new line we first need to clear the current nextLine by reading it:
scanner.nextLine();
// ----
System.out.println("Please enter a line"); // PROMPT
// get line with "nextLine()"
String l = scanner.nextLine();
// do something with the input
System.out.println("The number entered was: " + n);
System.out.println("The decimal entered was: " + f);
System.out.println("The word entered was: " + s);
System.out.println("The line entered was: " + l);
}
catch (InputMismatchException e) {
System.out.println("\tInvalid input entered. Please enter the specified input");
}
scanner.close(); // close the scanner so it doesn't leak
}
}
注意:其他类,如Console和DataInputStream也是可行的替代方案。
Console具有一些强大的功能,例如读取密码的能力,但是,并不是所有IDE(如Eclipse)中都可用。出现这种情况的原因是Eclipse将应用程序作为后台进程运行,而不是作为带有系统控制台的顶级进程运行。这里有一个关于如何实现Console类的有用示例的链接。
DataInputStream主要用于以一种与机器无关的方式从底层输入流中读取原始数据类型的输入。DataInputStream通常用于读取二进制数据。它还为读取某些数据类型提供了方便的方法。例如,它有一个方法来读取UTF字符串,其中可以包含任意数量的行。
然而,它是一个更复杂的类,很难实现,所以不建议初学者使用。这里有一个链接到一个如何实现DataInputStream的有用示例。
其他回答
您可以根据需求使用以下任何选项。
扫描仪类
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方法已弃用。要获得String值,您应该使用前面的BufferedReader解决方案
控制台类
import java.io.Console;
//...
Console console = System.console();
String s = console.readLine();
int i = Integer.parseInt(console.readLine());
显然,这种方法在某些ide中不能很好地工作。
你可以做一个简单的程序,要求用户的名字和打印任何回复使用输入。
或者让用户输入两个数字,你可以加、乘、减或除这些数字,并打印出用户输入的答案,就像计算器的行为一样。
你需要Scanner类。你必须导入java。util。scanner;在你需要使用的代码中
Scanner input = new Scanner(System.in);
Input是一个变量名。
Scanner input = new Scanner(System.in);
System.out.println("Please enter your name : ");
s = input.next(); // getting a String value
System.out.println("Please enter your age : ");
i = input.nextInt(); // getting an integer
System.out.println("Please enter your salary : ");
d = input.nextDouble(); // getting a double
看看这有什么不同:input.next();, i = input.nextInt();, d = input.nextDouble();
根据String类型,int和double类型以同样的方式变化。不要忘记代码顶部的import语句。
请参见博客文章“扫描器类和获取用户输入”。
以下是一个更完善的公认答案,解决了两个常见需求:
重复收集用户输入,直到输入退出值 处理无效输入值(本例中是非整数)
Code
package inputTest;
import java.util.Scanner;
import java.util.InputMismatchException;
public class InputTest {
public static void main(String args[]) {
Scanner reader = new Scanner(System.in);
System.out.println("Please enter integers. Type 0 to exit.");
boolean done = false;
while (!done) {
System.out.print("Enter an integer: ");
try {
int n = reader.nextInt();
if (n == 0) {
done = true;
}
else {
// do something with the input
System.out.println("\tThe number entered was: " + n);
}
}
catch (InputMismatchException e) {
System.out.println("\tInvalid input type (must be an integer)");
reader.nextLine(); // Clear invalid input from scanner buffer.
}
}
System.out.println("Exiting...");
reader.close();
}
}
例子
Please enter integers. Type 0 to exit.
Enter an integer: 12
The number entered was: 12
Enter an integer: -56
The number entered was: -56
Enter an integer: 4.2
Invalid input type (must be an integer)
Enter an integer: but i hate integers
Invalid input type (must be an integer)
Enter an integer: 3
The number entered was: 3
Enter an integer: 0
Exiting...
注意,如果没有nextLine(),错误的输入将在无限循环中重复触发相同的异常。您可能希望根据具体情况使用next(),但要知道像这样带有空格的输入将生成多个异常。
还有一个细节。如果你不想冒内存/资源泄漏的风险,你应该在完成后关闭扫描仪流:
myScanner.close();
注意,java 1.7及以后的版本将此作为编译警告捕获(不要问我是如何知道的:-)
最简单的方法之一是使用Scanner对象,如下所示:
import java.util.Scanner;
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a number: ");
int n = reader.nextInt(); // Scans the next token of the input as an int.
//once finished
reader.close();