我无法使用公共(public)方法检查非字符串值,例如 a-z 和 A-Z
Scanner input = new Scanner(System.in);
System.out.print("Enter your First Name: ");
String First_name = input.nextLine();
Scanner last = new Scanner(System.in);
System.out.print("Enter your Last Name: ");
String Last_name = last.nextLine();
这是公共(public)方法
public static boolean check_non_string_value (String First_name, String Last_name){
// dont know how to check the input here
}
最佳答案
您可以使用正则表达式,但自己循环遍历每个字符串并使用 Character.isLetter()
也相对简单检查每个字符:
for (char c : firstName.toCharArray()) {
if (!Character.isLetter(c))
return false;
}
for (char c : lastName.toCharArray()) {
if (!Character.isLetter(c))
return false;
}
return true;
请注意,我使用了更传统的名称:firstName
和 lastName
。您应该始终尝试遵循 Java 的命名约定(即使用 camelCase )。您的方法名称也应该是 checkNonStringValue
。
使用正则表达式,你可以这样做:
private static final Pattern letters = Pattern.compile("\\p{Alpha}+");
...
return letters.matcher(firstName).matches() &&
letters.matcher(lastName).matches();
\p{Alpha}
是一个预定义的字符类,意思是 [a-zA-Z]
。参见 Pattern
了解更多详情。
关于java - 检查java中的非字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19273666/