如何在Java中为用户输入分配变量?我应该使用扫描仪吗?

时间:2014-06-12 17:18:19

标签: java java.util.scanner

我是Java新手,这是我在该语言中尝试过的第一个程序。我已经搜索了一下,但似乎找不到如何使用扫描仪将用户输入分配给变量的可理解的解释。我不完全确定扫描仪是什么,这可能是问题的一部分。

我在这里阅读了文档(http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html)。它谈了很多关于reg ex的事情,我不需要它,让我觉得我可能会朝错误的方向看。非常感谢任何帮助,谢谢!

import java.util.*;

public final class Chapter_02 {
    public static void main(String[] args) {
        //Declare variables to be used (Height, Width, and Area)
        double length;
        double width;
        double area;

        //User input of length and width
        System.out.print("Please input the length of the property in feet:");
        width = ;
        System.out.print("Please input the length of the property in feet:");
        length = ;

        //Calculate area based on user input
        //Divide by number of feet in one acre
        area = (length * width) / 43560;

        //Additional spacing for readability
        System.out.println();
        System.out.println();

        //Post calculation result
        System.out.println("The property is " + area + " acres!");
    }
}    

2 个答案:

答案 0 :(得分:4)

尝试使用这个性感代码来获取尺寸:

Scanner scan = new Scanner(System.in);

//User input of length and width
System.out.print("Please input the width of the property in feet:");
width = scan.nextDouble();
System.out.print("Please input the length of the property in feet:");
length = scan.nextDouble();

答案 1 :(得分:0)

是的,您可以使用扫描仪或使用控制台:

Console console = System.console();
String inputWidth = console.readLine("Please input the length of the property in feet:");

然后将字符串转换为double:

double width = Double.parseDouble(inputWidth);