如何将用户输入分配给 Java 中的变量?我应该使用扫描仪吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24190289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I assign user input to a variable in Java? Should I be using scanner?
提问by Jordan Frankfurt
I am completely new to Java, this is the first program I have ever attempted in the language. I've googled around a bit, but can't seem to find an understandable explanation of how to use scanner to assign user input to a variable. I'm not entirely sure what scanner is, which is probably part of the problem.
我对 Java 完全陌生,这是我在该语言中尝试过的第一个程序。我已经用谷歌搜索了一下,但似乎无法找到有关如何使用扫描仪将用户输入分配给变量的可理解解释。我不完全确定扫描仪是什么,这可能是问题的一部分。
I've read the documentation here (http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html). It talks a lot about reg ex, which I do not need and makes me think I may be looking in the wrong direction. Any help would be much appreciated, thanks!
我已阅读此处的文档(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!");
}
}
采纳答案by Greg
Try this sexy code on for size:
试试这个性感的代码:
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();
回答by mmohab
yes you can use the scanner or use console:
是的,您可以使用扫描仪或使用控制台:
Console console = System.console();
String inputWidth = console.readLine("Please input the length of the property in feet:");
and then convert the string to double:
然后将字符串转换为双精度:
double width = Double.parseDouble(inputWidth);