我是Java的新手,我想知道如何检查用户是否只键入了他/她姓名的字母。如果他们没有再问他们的姓名。
System.out.print("Welcome - What is your family's surname? ");
familySurname = keyboard.nextLine();
while (familySurname.isEmpty())
{
System.out.print("Invalid name - What is your family's surname? ");
familySurname = keyboard.nextLine();
if (familySurname.matches("[a-zA-Z]"))
{
System.out.println("Invalid Input.");
}
}
这是我到目前为止的代码,但它仍在接受数字。
答案 0 :(得分:4)
你的循环条件应该是:
while (!familySurname.matches("[a-zA-Z]+")){
System.out.print("Invalid name - What is your family's surname? ");
familySurname = keyboard.nextLine();
}
答案 1 :(得分:1)
if (!familySurname.matches("[a-zA-Z]+")) // need ! and +
答案 2 :(得分:1)
或速度 -
public static boolean isAlpha(final String value) {
if(value == null || value.isEmpty()){
return false;
}
char[] chars = value.toCharArray();
for (char c : chars) {
if(!Character.isLetter(c)) {
return false;
}
}
return true;
}
您的代码段可以修改为 -
while (!isAlpha(familySurname)){
System.out.print("Invalid name - What is your family's surname? ");
familySurname = keyboard.nextLine();
}
答案 3 :(得分:0)
System.out.print("Welcome - What is your family's surname? ");
familySurname = keyboard.nextLine();
while (familySurname.isEmpty())
{
System.out.print("Invalid name - What is your family's surname? ");
familySurname = keyboard.nextLine();
if (!familySurname.isLetter(source.charAt(i)))
return "";
}
答案 4 :(得分:0)
你不想捕捉和修剪它吗?
System.out.print("Welcome - What is your family's surname? ");
String familySurname = "";
while (familySurname.length() == 0) { // while we don't have a surname.
if (keyboard.hasNextLine()) { // check that there is a line of input.
familySurname = keyboard.nextLine().trim(); // get the line and trim() it.
for (char c : familySurname.toCharArray()) {
if (!Character.isLetter(c)) { // Test for not a letter.
System.out.print("Invalid name - What is your family's surname? ");
familySurname = "";
break;
}
}
}
}