Java 字符输入验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29761008/
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
Java character input validation
提问by danielG
I want to validate a single character in a java application.
I don't want the user to be able to enter a character outside the range [a - p]
(ignoring uppercase or lowercase) or numbers
.
我想验证 Java 应用程序中的单个字符。我不希望用户能够输入范围之外的字符[a - p]
(忽略大写或小写)或numbers
.
Scanner input = new Scanner(System.in);
System.out.print("Choose letter in range [a - p]");
letter = input.next().charAt(0);
Any ideas?
有任何想法吗?
回答by Dyrandz Famador
you can use regexto filter input
您可以使用正则表达式来过滤输入
.matches("^[a-pA-P0-9]*$") //this will not allow outside range of [a-p A-P] or numbers
^
Assert position at start of the string
^
断言字符串开头的位置
-
Create a character range with the adjascent tokens
-
使用相邻的标记创建字符范围
a-p
A single character in the range between a
and p
(case sensitive)
a-p
a
和 之间范围内的单个字符p
(区分大小写)
A-P
A single character in the range between A
and P
(case sensitive)
A-P
A
和 之间范围内的单个字符P
(区分大小写)
0-9
A single character in the range between 0 and 9
0-9
0 到 9 范围内的单个字符
*
Repeat previous token zero
to infinite
times, as many times as possible
*
重复前面的标识zero
来infinite
次,多次地
$
Assert position at end of the string
$
断言字符串末尾的位置
like this:
像这样:
Scanner input = new Scanner(System.in);
System.out.print("Choose letter in range [a - p]");
letter = input.next().charAt(0);
if (Character.toString(letter).matches("^[a-pA-P0-9]*$")) {
System.out.println("valid input");
}else{
System.out.println("invalid input");
}
回答by Mark
you can encapsulate it with a while loop to check if the letter is in the range or not and just keep asking the user to input a letter
你可以用while循环封装它来检查字母是否在范围内,并不断要求用户输入一个字母
do {
System.out.print("Choose letter in range [a - p]"); letter = input.next().charAt(0);
} while (letter is not in range of [a-p]); // pseudo code
回答by Shar1er80
If you're not familiar with regex, simple checks on the input can take care of it.
如果您不熟悉正则表达式,只需对输入进行简单检查即可解决。
System.out.print("Choose letter in range [a - p]");
String letter = input.nextLine();
if (letter.length() == 1 && ('a' <= letter.charAt(0) && letter.charAt(0) <= 'p')) {
System.out.println(letter);
} else {
System.out.println("Invalid input");
}
I'm using nextLine() in the event that multiple characters are accidentally entered, which is why I check that the length of letter == 1 and that the letter falls in the range that I want, otherwise it is invalid input.
如果不小心输入了多个字符,我将使用 nextLine(),这就是为什么我检查字母 == 1 的长度以及字母是否在我想要的范围内,否则就是无效输入。