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

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


当前回答

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

其他回答

下面是获取键盘输入的方法:

Scanner scanner = new Scanner (System.in);
System.out.print("Enter your name");  
String name = scanner.next(); // Get what the user types.
import java.util.Scanner;

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

        System.out.print("Name : ");
        String name = input.next();
        System.out.print("Last Name : ");
        String lname = input.next();
        System.out.print("Age : ");
        byte age = input.nextByte();

        System.out.println(" " );
        System.out.println(" " );

        System.out.println("Firt Name: " + name);
        System.out.println("Last Name: " + lname);
        System.out.println("      Age: " + age);
    }
}
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

您可以根据需求使用以下任何选项。

扫描仪类

import java.util.Scanner; 
//...
Scanner scan = new Scanner(System.in);
String s = scan.next();
int i = scan.nextInt();

BufferedReader和InputStreamReader类

import java.io.BufferedReader;
import java.io.InputStreamReader;
//...
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
int i = Integer.parseInt(s);

DataInputStream类

import java.io.DataInputStream;
//...
DataInputStream dis = new DataInputStream(System.in);
int i = dis.readInt();

DataInputStream类中的readLine方法已弃用。要获得String值,您应该使用前面的BufferedReader解决方案


控制台类

import java.io.Console;
//...
Console console = System.console();
String s = console.readLine();
int i = Integer.parseInt(console.readLine());

显然,这种方法在某些ide中不能很好地工作。

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