2017-01-28 58 views
0

我一直在嘗試驗證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"); 
     } 
    } 
} 

回答

0

您可以利用while (true) { }循環。提示用戶輸入,如第一次詢問,然後在while(true)循環內使用if else來檢查id是否有效。在if語句執行的情況下,如果ID有效,則放break;,然後在else中執行類似System.out.println("Wrong ID, please enter it again: ");的操作,然後再次覆蓋ID掃描。

做這好像是會產生這樣的結果:

  1. 首先你問ID,如果ID是有效的程序不告訴你你犯了錯東西。

  2. 如果ID是錯的,它告訴你它會要求你再次輸入它,如果你輸入正確的話,它會退出並像第一次輸入時一樣正確。

  3. 如果它仍然不正確,它將執行第2點開頭所描述的內容。每當你輸入錯誤時,它會做同樣的事情,一旦它正確,它將停止。

+0

謝謝!我讚賞這個建議並使用標誌值。我花了一段時間,但我現在得到它:) –

+0

@NicoRobin沒問題,很高興聽到你修好了! –

-1

首先,我不認爲你需要指定== true,這是在while循環暗示。

其次,想一下這個順序。如果他們得到了錯誤一次然後糾正之後,代碼將如何知道它是否正確?目前它剛剛退出。

+0

謝謝!我的訂購是錯誤的,這也讓我想到重新安排最後一部分。它正在工作:) –

相關問題