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

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


当前回答

这是一个使用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;
            }
        }
    }   
}    

其他回答

您可以使用Scanner获取用户输入。您可以使用正确的方法对不同的数据类型使用正确的输入验证,例如对String使用next(),对Integer使用nextInt()。

import java.util.Scanner;

Scanner scanner = new Scanner(System.in);

//reads the input until it reaches the space
System.out.println("Enter a string: ");
String str = scanner.next();
System.out.println("str = " + str);

//reads until the end of line
String aLine = scanner.nextLine();

//reads the integer
System.out.println("Enter an integer num: ");
int num = scanner.nextInt();
System.out.println("num = " + num);

//reads the double value
System.out.println("Enter a double: ");
double aDouble = scanner.nextDouble();
System.out.println("double = " + aDouble);


//reads the float value, long value, boolean value, byte and short
double aFloat = scanner.nextFloat();
long aLong = scanner.nextLong();
boolean aBoolean = scanner.nextBoolean();
byte aByte = scanner.nextByte();
short aShort = scanner.nextShort();

scanner.close();

最简单的方法之一是使用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();
Scanner input=new Scanner(System.in);
int integer=input.nextInt();
String string=input.next();
long longInteger=input.nextLong();

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

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