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

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


当前回答

import java.util.Scanner; 

class Daytwo{
    public static void main(String[] args){
        System.out.println("HelloWorld");

        Scanner reader = new Scanner(System.in);
        System.out.println("Enter the number ");

        int n = reader.nextInt();
        System.out.println("You entered " + n);

    }
}

其他回答

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

最好的两个选项是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的有用示例。

下面是使用java.util.Scanner的问题中的程序:

import java.util.Scanner;

public class Example {
    public static void main(String[] args) {
        int input = 0;
        System.out.println("The super insano calculator");
        System.out.println("enter the corrosponding number:");
        Scanner reader3 = new Scanner(System.in);
        System.out.println(
            "1. Add | 2. Subtract | 3. Divide | 4. Multiply");

        input = reader3.nextInt();

        int a = 0, b = 0;

        Scanner reader = new Scanner(System.in);
        System.out.println("Enter the first number");
        // get user input for a
        a = reader.nextInt();

        Scanner reader1 = new Scanner(System.in);
        System.out.println("Enter the scend number");
        // get user input for b
        b = reader1.nextInt();

        switch (input){
            case 1:  System.out.println(a + " + " + b + " = " + add(a, b));
                     break;
            case 2:  System.out.println(a + " - " + b + " = " + subtract(a, b));
                     break;
            case 3:  System.out.println(a + " / " + b + " = " + divide(a, b));
                     break;
            case 4:  System.out.println(a + " * " + b + " = " + multiply(a, b));
                     break;
            default: System.out.println("your input is invalid!");
                     break;
        }
    }

    static int      add(int lhs, int rhs) { return lhs + rhs; }
    static int subtract(int lhs, int rhs) { return lhs - rhs; }
    static int   divide(int lhs, int rhs) { return lhs / rhs; }
    static int multiply(int lhs, int rhs) { return lhs * rhs; }
}

这是一个使用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;
            }
        }
    }   
}    
import java.util.Scanner; 

class Daytwo{
    public static void main(String[] args){
        System.out.println("HelloWorld");

        Scanner reader = new Scanner(System.in);
        System.out.println("Enter the number ");

        int n = reader.nextInt();
        System.out.println("You entered " + n);

    }
}