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

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


当前回答

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);
    }
}

其他回答

使用JOptionPane就可以实现。

Int a =JOptionPane.showInputDialog(null,"Enter number:");

最简单的方法之一是使用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();
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 scanner = new Scanner (System.in);
System.out.print("Enter your name");  
String name = scanner.next(); // Get what the user types.

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

扫描仪类

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中不能很好地工作。