[英]How to keep Text print only once when asking a user to re-enter some string in loop in Java
I want to ask user to enter a number in type String, then check if it is number and if it's not then ask again to re-enter the string. 我想让用户在String类型中输入一个数字,然后检查它是否为数字,如果不是,则再次要求重新输入该字符串。 I have a code like this:
我有这样的代码:
System.out.print("Enter first number: ");
firstNum = scan.next();
while(validateNum(firstNum) == false) {
System.out.print("Please, enter number only: ");
firstNum = scan.next();
}
here's the validateNum method : 这是validateNum方法:
private static boolean validateNum(String num) {
if (num.matches("[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?")){
return true;
}
return false;
}
But the problem is that when I test it and enter some text with spaces it prints "Please, enter a number only" as many times as many spaces are in entered string. 但是问题是,当我测试它并输入一些带有空格的文本时,它会打印“请仅输入一个数字”,这是输入字符串中出现的空格的次数。 I tried to remove spaces from string and then check it but it still gives many prints.
我试图从字符串中删除空格,然后检查它,但它仍然可以打印出许多文字。
You are using scan.next()
. 您正在使用
scan.next()
。 This returns what comes before a space. 这将返回空格之前的内容。 You want
scan.nextLine()
to scan the entire line the user inputs 您希望
scan.nextLine()
扫描用户输入的整行
Here is the docs on the Scanner
class and it's methods. 这是
Scanner
类及其方法的文档 。
In short: 简而言之:
next()
: Scans for the next complete token next()
:扫描下一个完整令牌
nextLine()
: Scans the complete line nextLine()
:扫描整行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.