[英]How can I let a user hit enter for a default value using the Scanner in java?
Lets say I wanted to have the following prompt: 让我们说我想要以下提示:
"Enter the number of iterations (400):" “输入迭代次数(400):”
Where, the user can enter an integer or simply hit enter for the default of 400. 其中,用户可以输入一个整数或只需按Enter键,默认值为400。
How can I implement the default value in Java using the Scanner class? 如何使用Scanner类在Java中实现默认值?
public static void main(String args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of iterations (400): ");
input.nextInt();
}
As you can see, I must have "nextInt()", how can I do something like "nextInt or a return?", in which case if it is a return I'll default the value to 400. 正如你所看到的,我必须有“nextInt()”,我怎么能做类似“nextInt或return?”的事情,在这种情况下如果它是一个返回我将默认值为400。
Can anyone point me in the right direction? 谁能指出我正确的方向?
I agree with @pjp for answering your question directly on how to adapt the scanner (I gave him an up-vote), but I get the impression using Scanner is kinda overkill if you're only reading in one value from stdin. 我同意@pjp直接回答你关于如何调整扫描仪的问题(我给了他一个向上投票),但如果你只是从stdin中读取一个值,我会得到使用Scanner的印象有点矫枉过正。 Scanner strikes me as something you would more want to use to read a series of inputs (if that's what you're doing, my apologies), but otherwise why not just read stdin directly?
扫描仪让我觉得你更想要用来读取一系列输入(如果这就是你正在做的事情,我的道歉),但另外为什么不直接读取stdin? Although now that I look at it, it's kinda verbose ;)
虽然我现在看着它,但它有点冗长;)
You should also probably handle that IOException better than I did... 您也应该比我更好地处理IOException ...
public static void main(String[] args) throws IOException
{
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the number of iterations (400): ");
int iterations = 400;
String userInput = input.readLine();
//if the user entered non-whitespace characters then
//actually parse their input
if(!"".equals(userInput.trim()))
{
try
{
iterations = Integer.parseInt(userInput);
}
catch(NumberFormatException nfe)
{
//notify user their input sucks ;)
}
}
System.out.println("Iterations = " + iterations);
}
As we found out earlier Scanner doesn't treat new line as a token. 正如我们之前发现的,Scanner不会将新行视为令牌。 To get around this we can call
nextLine
and then match it using a regular expression. 为了解决这个问题,我们可以调用
nextLine
,然后使用正则表达式进行匹配。
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int val = 400;
String line = scanner.nextLine();
if (line.matches("\\d+")) {
Integer val2 = Integer.valueOf(line);
val=val2;
}
System.out.println(val);
}
This kind of makes the scanner redundant. 这种方式使扫描仪变得多余。 You might as well call
input.readLine()
. 你也可以调用
input.readLine()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.