public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String regex = "[a-zA-Z ]+$";
String regex1 = "\\d[0-9]|[1-9]";
String regex2 = "^[a-zA-Z0-9 ]+$";
String petName;
StringBuilder output = new StringBuilder();
do {
System.out.print("\nHow Many Pet do you have? Give from 1-3:");
petName = input.nextLine();
if (petName.isEmpty()) {
System.out.println("Number field should not be Empty.");
} else if (!petName.matches(regex1)) {
System.out.println("Please Enter A Valid Number!");
}
} while (!petName.matches(regex1));
do {
Integer.parseInt(petName);
String[] pets = new String[Integer.parseInt(petName)];
System.out.print("\nList Down All Your Pet Names:\n");
for (int i = 0; i < pets.length; i++) {
System.out.print("\nPET" + (i + 1) + ":");
pets[i] = input.nextLine();
if (pets[i].isEmpty()) {
System.out.print("String field should not be Empty.");
} else if (!pets[i].matches(regex)) {
System.out.print("Please input a valid String.");
}
}
output.append("\nThese Are The List Of The Pets You Have:");
for (int i = 0; i < pets.length; i++) {
output.append("\nPET:").append(i + 1).append(" ").append(pets);
}
} while (!petName.matches(regex));
System.out.println(output);
}
我在上面的代碼有點問題。forloop下的用戶驗證輸入
我想要的是如果我輸入一個整數然後它會提示我這條消息「請輸入一個有效的字符串」,或者如果我沒有在字段中輸入任何內容,那麼它會提示我這個另一個消息「不是空的「。但是,即使我在字段中輸入了一個字符串值,它仍然會提示「請輸入一個有效的字符串」,並且每當我按下回車鍵時,循環仍會一遍又一遍地執行相同的操作。
什麼是假設這個正則表達式'「[a-zA-Z] + $」'?在此添加一些輸入示例。 – AxelH
for(int i = 0; i
這是我用來驗證字符串的代碼。 –