我试图创建一个计算器,但我不能让它工作,因为我不知道如何获得用户输入。

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


当前回答

您可以使用Scanner获取用户输入。您可以使用正确的方法对不同的数据类型使用正确的输入验证,例如对String使用next(),对Integer使用nextInt()。

import java.util.Scanner;

Scanner scanner = new Scanner(System.in);

//reads the input until it reaches the space
System.out.println("Enter a string: ");
String str = scanner.next();
System.out.println("str = " + str);

//reads until the end of line
String aLine = scanner.nextLine();

//reads the integer
System.out.println("Enter an integer num: ");
int num = scanner.nextInt();
System.out.println("num = " + num);

//reads the double value
System.out.println("Enter a double: ");
double aDouble = scanner.nextDouble();
System.out.println("double = " + aDouble);


//reads the float value, long value, boolean value, byte and short
double aFloat = scanner.nextFloat();
long aLong = scanner.nextLong();
boolean aBoolean = scanner.nextBoolean();
byte aByte = scanner.nextByte();
short aShort = scanner.nextShort();

scanner.close();

其他回答

您可以根据需求使用以下任何选项。

扫描仪类

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中不能很好地工作。

您可以使用BufferedReader获取用户输入。

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String accStr;  

System.out.println("Enter your Account number: ");
accStr = br.readLine();

它将在accStr中存储一个String值,因此您必须使用Integer.parseInt将其解析为int。

int accInt = Integer.parseInt(accStr);

还有一个细节。如果你不想冒内存/资源泄漏的风险,你应该在完成后关闭扫描仪流:

myScanner.close();

注意,java 1.7及以后的版本将此作为编译警告捕获(不要问我是如何知道的:-)

获取用户输入的最简单方法是使用Scanner。下面是一个如何使用它的例子:

import java.util.Scanner;
public class main {
public static void main(String[]args) {
Scanner sc=new Scanner(System.in);
int a;
String b;
System.out.println("Type an integer here: ");
a=sc.nextInt();
System.out.println("Type anything here:");
b=sc.nextLine();

代码行导入java.util.Scanner;告诉程序程序员将在他们的代码中使用用户输入。如它所说,它导入了扫描仪实用程序。Scanner sc=new Scanner(System.in);告诉程序启动用户输入。在你这样做之后,你必须创建一个没有值的字符串或整数,然后把它们放在一行a=sc.nextInt();或= sc.nextLine();。这为变量提供了用户输入的值。然后可以在代码中使用它。希望这能有所帮助。

然后,Add在main()旁边抛出IOException

DataInputStream input = new DataInputStream(System.in);
System.out.print("Enter your name");
String name = input.readLine();