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

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


当前回答

您可以使用Scanner类或Console类

Console console = System.console();
String input = console.readLine("Enter input:");

其他回答

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

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

最简单的方法之一是使用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();

可能是这样的……

public static void main(String[] args) {
    Scanner reader = new Scanner(System.in);

    System.out.println("Enter a number: ");
    int i = reader.nextInt();
    for (int j = 0; j < i; j++)
        System.out.println("I love java");
}
Scanner input=new Scanner(System.in);
int integer=input.nextInt();
String string=input.next();
long longInteger=input.nextLong();

在java中输入是非常简单的,你所要做的就是:

import java.util.Scanner;

class GetInputFromUser
{
    public static void main(String args[])
    {
        int a;
        float b;
        String s;

        Scanner in = new Scanner(System.in);

        System.out.println("Enter a string");
        s = in.nextLine();
        System.out.println("You entered string " + s);

        System.out.println("Enter an integer");
        a = in.nextInt();
        System.out.println("You entered integer " + a);

        System.out.println("Enter a float");
        b = in.nextFloat();
        System.out.println("You entered float " + b);
    }
}