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

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


当前回答

最好的两个选项是BufferedReader和Scanner。

使用最广泛的方法是Scanner,我个人更喜欢它,因为它的简单性和易于实现,以及它将文本解析为原始数据的强大实用程序。

使用扫描仪的优点

易于使用的Scanner类 轻松输入数字(int, short, byte, float, long和double) 异常是未检查的,这更方便。这取决于程序员的文明,并指定或捕获异常。 是否能够读取行、空格和正则表达式分隔的令牌

BufferedInputStream的优点

BufferedInputStream是关于读取数据块,而不是一次读取一个字节 可以读取字符,字符数组和行吗 抛出检查过的异常 快速的性能 同步(你不能在线程间共享扫描器)


总的来说,每种输入法都有不同的目的。

如果你输入大量的数据BufferedReader可能 对你更好 如果你输入大量的数字,扫描仪做自动解析 这很方便

对于更基本的用途,我建议使用Scanner,因为它更容易使用,也更容易编写程序。下面是一个快速创建扫描器的示例。下面我将提供一个关于如何使用Scanner的全面示例

Scanner scanner = new Scanner (System.in); // create scanner
System.out.print("Enter your name");       // prompt user
name = scanner.next();                     // get user input

(有关BufferedReader的更多信息,请参阅如何使用BufferedReader,并参阅读取字符行)


java.util.Scanner

import java.util.InputMismatchException; // import the exception catching class
import java.util.Scanner; // import the scanner class

public class RunScanner {

    // main method which will run your program
    public static void main(String args[]) {

        // create your new scanner
        // Note: since scanner is opened to "System.in" closing it will close "System.in". 
        // Do not close scanner until you no longer want to use it at all.
        Scanner scanner = new Scanner(System.in);

        // PROMPT THE USER
        // Note: when using scanner it is recommended to prompt the user with "System.out.print" or "System.out.println"
        System.out.println("Please enter a number");

        // use "try" to catch invalid inputs
        try {

            // get integer with "nextInt()"
            int n = scanner.nextInt();


            System.out.println("Please enter a decimal"); // PROMPT
            // get decimal with "nextFloat()"
            float f = scanner.nextFloat();


            System.out.println("Please enter a word"); // PROMPT
            // get single word with "next()"
            String s = scanner.next();

            // ---- Note: Scanner.nextInt() does not consume a nextLine character /n 
            // ---- In order to read a new line we first need to clear the current nextLine by reading it:
            scanner.nextLine(); 
            // ----
            System.out.println("Please enter a line"); // PROMPT
            // get line with "nextLine()"
            String l = scanner.nextLine();


            // do something with the input
            System.out.println("The number entered was: " + n);
            System.out.println("The decimal entered was: " + f);
            System.out.println("The word entered was: " + s);
            System.out.println("The line entered was: " + l);


        }
        catch (InputMismatchException e) {
            System.out.println("\tInvalid input entered. Please enter the specified input");
        }

        scanner.close(); // close the scanner so it doesn't leak
    }
}

注意:其他类,如Console和DataInputStream也是可行的替代方案。

Console具有一些强大的功能,例如读取密码的能力,但是,并不是所有IDE(如Eclipse)中都可用。出现这种情况的原因是Eclipse将应用程序作为后台进程运行,而不是作为带有系统控制台的顶级进程运行。这里有一个关于如何实现Console类的有用示例的链接。

DataInputStream主要用于以一种与机器无关的方式从底层输入流中读取原始数据类型的输入。DataInputStream通常用于读取二进制数据。它还为读取某些数据类型提供了方便的方法。例如,它有一个方法来读取UTF字符串,其中可以包含任意数量的行。

然而,它是一个更复杂的类,很难实现,所以不建议初学者使用。这里有一个链接到一个如何实现DataInputStream的有用示例。

其他回答

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...");
            }
        }
    }
}
Scanner input=new Scanner(System.in);
int integer=input.nextInt();
String string=input.next();
long longInteger=input.nextLong();

您可以使用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类。你必须导入java。util。scanner;在你需要使用的代码中

Scanner input = new Scanner(System.in);

Input是一个变量名。

Scanner input = new Scanner(System.in);

System.out.println("Please enter your name : ");
s = input.next(); // getting a String value

System.out.println("Please enter your age : ");
i = input.nextInt(); // getting an integer

System.out.println("Please enter your salary : ");
d = input.nextDouble(); // getting a double

看看这有什么不同:input.next();, i = input.nextInt();, d = input.nextDouble();

根据String类型,int和double类型以同样的方式变化。不要忘记代码顶部的import语句。

请参见博客文章“扫描器类和获取用户输入”。