Evaluating result for mastermind comparison I'm implementing a Java version of the game Mastermind. 

My version uses numbers to represent colors, for example 2315. This function compares a string of numbers to the secret code the object stored. It works, but I'm wondering if this could be done in a more elegant way.

public Answer evaluate(String guess) {
    boolean[] codeUsed = new boolean[code.length()];
    boolean[] guessUsed = new boolean[guess.length()];

    int correct = 0;
    int match = 0;

    // Compare correct color and position
    for (int i = 0; i &lt; code.length(); i++) {
        if (code.charAt(i) == guess.charAt(i)) {
            correct++;
            codeUsed[i] = guessUsed[i] = true;
        }
    }

    // Compare matching colors for "pins" that were not used
    for (int i = 0; i &lt; code.length(); i++) {
        for (int j = 0; j &lt; guess.length(); j++) {
            if (!codeUsed[i] &amp;&amp; !guessUsed[j] &amp;&amp; code.charAt(i) == guess.charAt(j)) {
                match++;
                codeUsed[i] = guessUsed[j] = true;
                break;
            }
        }
    }

    return new Answer(guess, correct, match, guess.length() - correct - match);
}
The algorithm is short and concise. There might be a more clever way to do it, but it would likely be less readable. 

This code will break if the guess is not the same length as the code. An empty string causes an out of out of bounds exception. A string longer than the code could cause other problems. You don't show what Answer is, but it looks like the last argument is the number of incorrect pins. This could lead to having more incorrect pins than there are in the code. You need to protect against each of these cases.

Since you are using strings, the value could contain characters other than digits. A guess with invalid characters should be treated differently than an incorrect guess.

You can add a check before the second loop to see if the all of the characters are correct. In that case you would skip over a N x M loop.