如何只允许用户输入字符并进行验证?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何只允许用户输入字符并进行验证?相关的知识,希望对你有一定的参考价值。
在下面的代码中,我试图让用户仅输入3个字母的3个单独输入。但是,我找不到让扫描仪只使用一个字符并验证a-zA-Z的方法。非常感谢您的帮助,
Scanner scnObj = new Scanner(System.in);
System.out.println("enter 3 letters");
char input1;
do {
input1 = scnObj.next(".").charAt(0);
if ((!Pattern.compile("[a-zA-Z]*").matcher(input1).matches())) {
System.out.println("Please try again.");
}
} while (!Pattern.compile("[a-zA-Z]*").matcher(input1).matches());
System.out.println("enter 2nd letter");
答案
我修改了您的一些代码:
Scanner scnObj = new Scanner(System.in);
System.out.println("enter 3 letters");
String input1 = null;
do {
input1 = scnObj.next();
if ((!Pattern.compile("[a-zA-Z]{1}").matcher(input1).matches())) {
System.out.println("Please try again.");
}
} while (!Pattern.compile("[a-zA-Z]{1}").matcher(input1).matches());
System.out.println("enter 2nd letter");
另一答案
工作示例:
Scanner scnObj = new Scanner(System.in);
String result = "";
do {
System.out.println("enter the letter number " + (result.length() + 1));
char input1 = scnObj.next(".").charAt(0);
if ((!Pattern.compile("[a-zA-Z]*").matcher(String.valueOf(input1)).matches())) {
System.out.println("Please try again.");
} else {
result += input1;
}
} while (result.length() < 3);
System.out.println("Your result is: " + result);
另一答案
您还可以将所需的正则表达式模式传递给Scanner.next()
方法。一个例子:
Scanner scnObj = new Scanner(System.in);
System.out.println("enter 3 letters");
List<Character> inputCharacters = new ArrayList<>(3);
String input1;
do {
try {
System.out.println("Enter letter no " + (inputCharacters.size() + 1));
input1 = scnObj.next("[a-zA-Z]");
inputCharacters.add(input1.charAt(0));
} catch (Exception nse) {
scnObj = new Scanner(System.in);
System.out.println("Please try again.");
}
} while (inputCharacters.size() < 3);
System.out.println("Input characters are " + inputCharacters);
另一答案
您可以直接使用System.in。
List<Character> chars = new ArrayList<>();
try {
// do until chars contains required number of characters
while (chars.size() < 3) {
// read in a character
char ch = (char) System.in.read();
// ignore EOL delimiters
if (ch == '
' || ch == '
') {
continue;
}
// if not a letter, clear input buffer and
// let the user know.
if (!Character.isLetter(ch)) {
int cnt = System.in.available();
System.in.readNBytes(cnt);
System.out.println("Invalid character encountered, please try again.");
} else {
chars.add(ch);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
System.out.println(chars);
以上是关于如何只允许用户输入字符并进行验证?的主要内容,如果未能解决你的问题,请参考以下文章
js 用正则表达式验证只允许输入数字,或者是数字后两位小数点,如何写?