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

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


当前回答

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

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

其他回答

以下是一个更完善的公认答案,解决了两个常见需求:

重复收集用户输入,直到输入退出值 处理无效输入值(本例中是非整数)

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(),但要知道像这样带有空格的输入将生成多个异常。

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

BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in));
String inputLine = bufferReader.readLine();
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

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

myScanner.close();

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

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

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