2012-10-24 68 views
1

我想使兩種方法,其他方法運行良好。麻煩是僞匹配計數器,其中輸入應該是隨機數,例如5 4 3 2,用戶猜測輸入例如5 3 6 1,輸出將是:僞匹配:1並匹配:2.我不理解我在我的僞匹配方法中出錯。Java匹配計數器和僞匹配計數器

public int match(int[] guess) //Counts the number of matches 
{ 
    int count = 0; 

    for(int i = 0; i<3; i++) 
    { 
     if (lotteryNumbers[i] == guess[i]) 
     { 
      count++; 
     } 

    } 
    return count; 
} 
//First add psuedo counter for current program 
//Then modify for multiple variables. 

//Single slot to Single slot. 
public int psuedoMatch(int[] guess) 
{ 
    boolean arraysEqual = true; 
    int psuedoCount = 0; 

    //Determine same size: 
    if (lotteryNumbers.length != guess.length) 
    { 
     arraysEqual = false; 
    } 

    //Determine if elements contain same data: 

    while (arraysEqual && psuedoCount < 3) // guess.length 
    { 
     if (lotteryNumbers[psuedoCount] != guess[psuedoCount]) 
     { 
      arraysEqual = false; 
     } 
     psuedoCount++; 
    } 

    return psuedoCount; 
} 
+0

我們稱之爲「公牛和牛」遊戲=) – Juvanis

+0

是我的解決方案對你有用嗎? – Juvanis

回答

0

我猜你正在努力尋找這2個陣列, 的匹配數量,但相等的相對指數元素應該不同,以便我們可以將它們添加到僞計數器機制中。所以看看這個方法並試試吧:

public int psuedoMatch(int[] guess) 
{ 
    int psuedoCount = 0; 

    if (lotteryNumbers.length != guess.length) 
     return 0; 

    int size = lotteryNumbers.length; 

    // Determine if elements contain same data, but at different indexes! 

    for (int i = 0; i < size; i++) { 
     for (int j = 0; j < size; j++) { 
      // Denote the inequality check i != j 
      if (lotteryNumbers[i] == guess[j] && i != j) 
       psuedoCount++; 
     } 
    } 

    return psuedoCount; 
} 
+0

是的,這是我想要做的,謝謝你的幫助!我只是不明白爲什麼有一個嵌套的循環。 – user1770068

+0

@ user1770068使用嵌套for循環,因爲您需要在猜測數組中搜索彩票號碼的每個元素。 – Juvanis

0

我認爲下面是你正在嘗試做的:

public int psuedoMatch(int[] guess) {   
    int psuedoCount = 0; 

    //Determine same size: 
    if (lotteryNumbers.length != guess.length) { 
     return psuedoCount; 
    } 

    //Determine if elements contain same data: 

    for(int i=0; i<lotteryNumbers.length || psuedoCount < 3; i++) { 

     //I think you want to count all the matches till you have 3 matches 
     if (lotteryNumbers[psuedoCount] == guess[psuedoCount]) { 
      psuedoCount++; 
     }    
    } 

    return psuedoCount; 
}