我一直在嘗試驗證ID輸入。當ID無效時,它應該提示用戶再次輸入。但是,當ID是正確的,似乎運作良好。雖然無效驗證使我無限循環,或者在輸入時停止在那裏。如何提示用戶再次輸入正確的ID如果無效並在輸入正確時停止循環ID
public class validate {
public static void main (String [] args)
{
Scanner in = new Scanner(System.in);
boolean valid_len;
int letter = 0;
int digit = 0;
int k = 0;
int num_id = 0;
char chars;
String temp_dog_id = "";
System.out.print("Enter the Dog ID ");
temp_dog_id = in.nextLine();
num_id = temp_dog_id.length();
valid_len = (num_id >= 5) ? true : false;
String dog_id = temp_dog_id;
for (int i = 0; i< num_id; i++)
{
chars = temp_dog_id.charAt(i);
if (Character.isLetter(chars) && Character.isUpperCase(chars))
{
letter = dog_id.indexOf(chars, 1);
}
if (Character.isDigit(chars))
{
digit++;
}
}
while((num_id < 5 && valid_len))
{
System.out.print("Enter the Dog ID ");
temp_dog_id = in.nextLine();
System.out.println("Invalid. Enter the Id again. An example of ID of Dog would be eg. 1M434");
k++;
}
if ((letter == 1) && valid_len)
{
System.out.println("Correct");
}
}
}
謝謝!我讚賞這個建議並使用標誌值。我花了一段時間,但我現在得到它:) –
@NicoRobin沒問題,很高興聽到你修好了! –