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

如何在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();

其他回答

Scanner input = new Scanner(System.in);
String inputval = input.next();

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

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

public class Main {
    public static void main(String[] args) {
        System.out.println("Welcome to the best program in the world! ");
        while (true) {
            System.out.print("Enter a query: ");
            Scanner scan = new Scanner(System.in);
            String s = scan.nextLine();
            if (s.equals("q")) {
                System.out.println("The program is ending now ....");
                break;
            } else  {
                System.out.println("The program is running...");
            }
        }
    }
}

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

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

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

这是一个使用System.in.read()函数的简单代码。这段代码只是写出输入的内容。如果您只想获取一次输入,可以去掉while循环,如果您愿意,可以将答案存储在字符数组中。

package main;

import java.io.IOException;

public class Root 
{   
    public static void main(String[] args)
    {
        new Root();
    }

    public Root()
    {
        while(true)
        {
            try
            {
                for(int y = 0; y < System.in.available(); ++y)
                { 
                    System.out.print((char)System.in.read()); 
                }
            }
            catch(IOException ex)
            {
                ex.printStackTrace(System.out);
                break;
            }
        }
    }   
}