mardi 31 mai 2016

Nested Loop not working properly in Mastermind game

I recently started coding in Java and my coach gave me an exercise where I have to re-create the Mastermind game. To give an overview of this game: the computer creates an array with X random integers, and the user gets to input X integers as well. Location matters. The users scores "Gold" if he guesses an integer that is in the same spot as the computer generated array. If the integer is present in the array, but in the wrong spot, the users gets a "Silver" score. If the integer is not present in the array at all, the user gets a "NotFound" score. The final array should give the user a score for each place in the array, e.g. (Gold, Silver, NotFound)

I have tried to make a nested loop that scores the users guesses. It captures the score in a different array (yourScore[]). User guesses are captured in array "guessednums[]" and the computer generated array is called "nums[]". The size of all arrays has been set with a variable prior to the mentioned code.

What I want the code to do is to first check whether a user's guess matches with the computer choice on the same spot, and if that is the case set the matching space in the yourScore array to "Gold". Then, if the guess does not directly match, I want a loop to check whether the user guess is present in ANY place of the computer generated nums[] array, and to score it as "Silver" if that is the case. Finally, if this is not the case, I want the yourScore[] place to be set as "NotFound".

Matching guesses are properly scored as "Gold". The problem I am encountering is that sometimes the loop will not properly score a guess as "Silver", but instead mark it as "NotFound". I suspect that this has to do with the loop not properly initialising. I have read multiple questions on Stack Overflow and other articles as well, and played around with my code, but I keep running into similar issues.

I would love to get a second opinion on the code and see what I have done wrong.

for(int i = 0; i < size;  i++){ // Nested loop that scores the user entries as Gold/Silver/NotFound
            for(int j = 0; j < size; j++){
                if (guessednums[i] == nums[i]){
                yourScore[i] = "Gold";
                } else {
                    if (guessednums[i] == nums[j]){
                        yourScore[i] = "Silver";
                    } else if (guessednums[i] != nums[j]){
                        yourScore[i] = "NotFound";
                    } 
                }
            }
        }

Aucun commentaire:

Enregistrer un commentaire