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のユーザー確認入力
整数を入力すると、「有効な文字列を入力してください」というメッセージが表示されます。フィールドに何も入力しなかった場合、この別のメッセージが表示されます。空ではない "。しかし、たとえフィールドに文字列値を入力しても、 "有効な文字列を入力してください"というメッセージが表示され、Enterキーを押すたびに繰り返しループが繰り返されます。
この正規表現 '' [a-zA-Z] + $ "'はどういう意味ですか?ここで使用される入力の例をいくつか追加してください。 ( "\ nPET" +(i + 1)+ ":"); – AxelH
for(int i = 0; i
これは文字列の検証に使用するコードです。 –