[英]Prevent the user entering numbers in java Scanner?
I am having some trouble preventing the user from entering numbers with the scanner class. 我在阻止用户使用扫描仪类别输入数字时遇到一些麻烦。 This is what I have:
这就是我所拥有的:
package palindrome;
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String word;
String inverse = "";
System.out.println("Write a sentence or word: ");
while (!input.hasNext("[A-Za-z]+")) {
System.out.println("Not valid! Try again: ");
input.nextLine();
}
word = input.nextLine();
word = word.replaceAll("\\s+","");
word = word.toLowerCase();
int length = word.length();
length = length - 1;
for (int i = length; i >= 0; i--) {
inverse = inverse + word.charAt(i);
}
if (word.equals(inverse)) {
System.out.println("Is a palindrome.");
} else {
System.out.println("Is not a palindrome.");
}
}
}
Basically when I enter a word or sentence I want it to check if it has any numbers anywhere in the input, if it has then you need to enter another one until it doesn't. 基本上,当我输入单词或句子时,我希望它检查输入中是否有任何数字,如果有,那么您需要输入另一个,直到没有为止。 Here is an example of output:
这是输出示例:
Write a sentence or word: 写一个句子或单词:
--> 11 -> 11
Not valid! 无效! Try again:
再试一次:
--> 1 test -> 1次测试
Not valid! 无效! Try again:
再试一次:
--> test 1 ->测试1
Is not a palindrome. 不是回文。
As you can see it works for most cases, but when I enter a word FIRST and then a space followed by a number it evaluates it without the number. 如您所见,它在大多数情况下都有效,但是当我输入单词FIRST,然后输入空格后跟数字时,它会在没有数字的情况下进行评估。 I am assuming this is happening because in the while loop is checking for only input.hasNext but it should be input.hasNextLine I believe to check the entire string.
我假设发生这种情况是因为在while循环中仅检查input.hasNext,但应该将其输入。hasNextLine我相信要检查整个字符串。 However I cannot have any arguments if I do that.
但是,如果这样做,我将没有任何论据。 Help much appreciated!
帮助非常感谢!
将您的正则表达式从: [A-Za-z]+
更改为^[A-Za-z]+$
,以防止输入字符串中的任何数字
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.