2014-09-01 104 views
-1

我有一個數組有5個隨機數。像這樣:Java比較彩票號碼

int correct[] = {11,23,54,13,5}; 

我有另一個數組,用戶的猜測。像這樣:

int userGuesses[] = {23,5,5,11,50}; 

我想查找用戶猜錯lotter數字的次數,所以無法重複。 如果userGuesses有兩個相同的數字並且用戶猜測正確,但correct[]只有一個值,而不是兩個,那麼程序不應該對此進行計數。

這是我到目前爲止。

public static void main(String[] args) {   
    int correct = 0;   
    int good[] = {1,2,3,4,5};  
    int bad[] = {2,1,5,5,12,3};  

    for (int i = 0; i < 5; i++) { 
     if(good[i] == bad[i]){ 
      correct++; 
     } 
    }  

    System.out.println(correct);   
} 
+1

你應該有嵌套循環;第一個陣列的外部運行,第二個陣列的內部運行。 – Maroun 2014-09-01 11:49:30

+0

請給我看看新版本,然後我會接受它 – 2014-09-01 11:51:11

+0

請自己動手 – Antoniossss 2014-09-01 11:51:42

回答

3

嘗試是這樣的:

int correct = 0; 
int good[] = {1, 2, 3, 4, 5}; // correct answers 
int bad[] = {2, 1, 5, 5, 12, 3}; // user guesses 

for (int i = 0; i < good.length; i++) { 
    for (int j = 0; j < bad.length; j++) { 
     if (good[i] == bad[j]) { 
      correct++; 
      break; 
     } 
    } 
} 

System.out.println(correct); 

好吧,我寫了一個小型的Java程序和它的實際工作。實際答案應該是4,因爲用戶猜測(假設'壞'數組是用戶的猜測)數字:1,2,3和5,我們不計算兩次。

+1

它給出4,最重要的答案是3 – 2014-09-01 11:54:24

0

將要測試的值複製到臨時數組中。然後,在找到匹配項時更改臨時數組中的值。

int correct = 0; 
int[] temp_array = bad.clone();// copy values to be tested into temp array 

for(int i = 0; i < good.length; i++) 
{ 
    for(int j = 0; j < bad.length; j++) 
    { 
     if(good[i] == temp_array[j])// match found 
     { 
     correct++;// increment correct 
     temp_array[j] = -999;// change value to out-of-range 
     break; 
     } 
    } 
} 

System.out.println("number correct is " + correct);