2017-02-11 138 views
0

我對Java比較陌生。我試圖找出0-4的數字是否存儲在 大小爲5的數組中。該數組由用戶在0-4之間輸入整數填充。我已經成功設法確認用戶輸入的第一個數字在數組中,但是之後的數字沒有出現。 舉個例子:如果用戶輸入數字2,2,2,1,3,我會得到只有2出現在數組中作爲結果。如何檢查某些數字是否出現在數組中?

public static void checkEachNumber(int[] array) 
{ 
    int currentNum = 0; 
    for(int i = 0; i < array.length; i++) 
    { 
     for(int j = 0; j < array.length; j++) 
     { 
      currentNum = i; 
      if(currentNum == array[j]) 
      { 
       System.out.println(currentNum + " appears in the array"); 
       break; 
      } 
      else 
      { 
       System.out.println(currentNum + " doesn't appear in the array"); 
       break; 
      } 
     } 
    } 
} 

回答

2

要解決你的問題,你應該簡單地刪除已在陣列的其他部分使用。 考慮這樣的情況

ex。 2 1 4 3

當檢查i = 1時,它將首先將該值與2進行比較,以便它從循環中出來。

public static void checkEachNumber(int[] array) 
{ 
    int currentNum = 0; 
    for(int i = 0; i < array.length; i++) 
    { 
     int flag=0; 
     for(int j = 0; j < array.length; j++) 
     { 
      currentNum = i; 
      if(currentNum == array[j]) 
      { 
       System.out.println(currentNum + " appears in the array"); 
       flag=1; 
       break; 
      } 

     } 
     if(flag==0) 
     { 
       System.out.println("currentNum+"Doesn't appear in array"); 
     } 
    } 
} 
2

當您執行break語句時,循環會完全停止運行。在一般情況下,掃描匹配的方式是要看起來像這樣:

found_match = no 

for (... in ...) { 
    if (match) { 
     found_match = yes 
     break 
    } 
} 

if (found_match) { 
    do_found_match_stuff(); 
} 
+0

哦,對了,沒關係。我確實懷疑問題出現在休息聲明中。 –

相關問題