我只需要允许用户输入a-z范围内的字符。我当时在考虑使用if语句,但对我来说不起作用。
System.out.println("Please enter letters of the alphabet");
String input1 = scnObj.nextLine();
if (input1 != a-z) {
System.out.println("Please try again.");
}
else
{
System.out.println("Correct.");
}
您可以使用regexp。您的情况很简单,类似这样:
if(!Pattern.compile("[a-z]*").matcher(line).matches()){
System.out.println("Please try again.");
}
如果要同时包含大写字母,请修改条件,例如:
if(!Pattern.compile("[a-zA-Z]*").matcher(line).matches()){
System.out.println("Please try again.");
}
如果允许空间:
if(!Pattern.compile("[a-zA-Z\\s]*").matcher(line).matches()){
System.out.println("Please try again.");
}
无论如何,对于更复杂的情况,请阅读the java doc
您可以使用正则表达式,但更简单的解决方案可能是利用a
-z
中的字符在字符集表中呈线性级数增长的事实,并执行类似的操作...
String input1 = scnObj.nextLine();
if (!input1.trim().isEmpty()) {
char inputChar = input1.charAt(0);
if (inputChar >= 'a' && inputChar <= 'z') {
// Everything is good
} else {
// Everything is bad
}
}
这听起来像是正则表达式实现的最佳时机。如果您从未听过正则表达式,建议您签出this video。本质上,它用于匹配字符串中的模式。对于Java,您可以使用以下命令检查每个字符是否为小写字母:
System.out.println("Please enter letters of the alphabet");
String input1 = scnObj.nextLine();
if (!input1.matches("[a-z]*") {
System.out.println("Please try again.");
} else {
System.out.println("Correct.");
}
但是,如果要允许空格/连字符,则可能需要增加一些。祝你好运!