lundi 28 décembre 2015

Recursive method keeps running after the return statement

The code i have is for a method that will take an input string and will try to sort them into the correct order that an unknown preset code is in. When the method calls the current guess method it is finding out how many of the characters in the string are in the correct position.

Then the three conditionals will then determine what happens next. The element pegs[1] in the array is how many of the characters are in the correct position. So if the the correct positions is equal to the total characters then the correct order for the code has been found, and the method should end. If the new pegs is higher then it should call the method again and start from the next position. If the correct positions then the characters was in the correct place, so it should reset the code and call the method again moving to the next position in the array.

I have another method that is called before it that will find all of the characters that are in the code, and so it is using that as the basis for what to try. For example if the code is RYGB then the starting input for the method would be RBGY. It gets the code to into the correct order, RYGB and will print it but then it continues calling the method and will eventually crash due to the method calling an index out of the array size.

I can't seem to figure out why its happening, i thought it would end the method when the return statement is used, after it prints it out the code. However it will continue to call the sort code method. Any help on this problem is greatly appreciated!

public void sortCode(int position) {
    int currentBlackPegs = pegs[1];
    String inputCode = new String(unorderedCode);
    for(int i = 0; i < currentGuess.length(); i++) {
        unorderedCode[position] = unsortedColours[i];
        String orderedCode = new String(unorderedCode);
        System.out.println("The ordered codethat will be tried" + orderedCode);

        pegs = newGame.currentGuess(currentCode, orderedCode, codeLength);

        if(pegs[1] == codeLength) {
            System.out.println("The code has been found and is " + orderedCode);
            return;
        } 
        if(currentBlackPegs > pegs[1]) {
            unorderedCode = inputCode.toCharArray();
            pegs[1] = currentBlackPegs;
            sortCode(position+1);
        } 
        if(pegs[1] > currentBlackPegs) {
            sortCode(position+1);
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire