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

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


当前回答

你可以像这样使用BufferedReader获取用户输入:

    InputStreamReader inp = new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(inp);
    // you will need to import these things.

这就是应用它们的方法

    String name = br.readline(); 

因此,当用户在控制台中输入他的名字时,“字符串名称”将存储该信息。

如果它是一个你想要存储的数字,代码将像这样:

    int x = Integer.parseInt(br.readLine());

希望这能有所帮助!

其他回答

获取用户输入的最简单方法是使用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();。这为变量提供了用户输入的值。然后可以在代码中使用它。希望这能有所帮助。

您可以使用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();
class ex1 {    
    public static void main(String args[]){
        int a, b, c;
        a = Integer.parseInt(args[0]);
        b = Integer.parseInt(args[1]);
        c = a + b;
        System.out.println("c = " + c);
    }
}
// Output  
javac ex1.java
java ex1 10 20 
c = 30

要读取一行或字符串,你可以使用BufferedReader对象和InputStreamReader对象结合使用,如下所示:

BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in));
String inputLine = bufferReader.readLine();

你可以像这样使用BufferedReader获取用户输入:

    InputStreamReader inp = new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(inp);
    // you will need to import these things.

这就是应用它们的方法

    String name = br.readline(); 

因此,当用户在控制台中输入他的名字时,“字符串名称”将存储该信息。

如果它是一个你想要存储的数字,代码将像这样:

    int x = Integer.parseInt(br.readLine());

希望这能有所帮助!