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

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


当前回答

还有一个细节。如果你不想冒内存/资源泄漏的风险,你应该在完成后关闭扫描仪流:

myScanner.close();

注意,java 1.7及以后的版本将此作为编译警告捕获(不要问我是如何知道的:-)

其他回答

在这里,程序要求用户输入一个数字。在此之后,程序打印数字的数字和数字的和。

import java.util.Scanner;

public class PrintNumber {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int num = 0;
        int sum = 0;

        System.out.println(
            "Please enter a number to show its digits");
        num = scan.nextInt();

        System.out.println(
            "Here are the digits and the sum of the digits");
        while (num > 0) {
            System.out.println("==>" + num % 10);
            sum += num % 10;
            num = num / 10;   
        }
        System.out.println("Sum is " + sum);            
    }
}

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

BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in));
String inputLine = bufferReader.readLine();
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。下面是一个如何使用它的例子:

import java.util.Scanner;
public class main {
public static void main(String[]args) {
Scanner sc=new Scanner(System.in);
int a;
String b;
System.out.println("Type an integer here: ");
a=sc.nextInt();
System.out.println("Type anything here:");
b=sc.nextLine();

代码行导入java.util.Scanner;告诉程序程序员将在他们的代码中使用用户输入。如它所说,它导入了扫描仪实用程序。Scanner sc=new Scanner(System.in);告诉程序启动用户输入。在你这样做之后,你必须创建一个没有值的字符串或整数,然后把它们放在一行a=sc.nextInt();或= sc.nextLine();。这为变量提供了用户输入的值。然后可以在代码中使用它。希望这能有所帮助。

使用JOptionPane就可以实现。

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