简体   繁体   中英

Why do I get a Stackoverflow Error?

I have a little recursive algorithm which should guess a number. I call the method guessNumber and give a number and a lower value than the number and a higher value than the number. If the value is higher than the middle of area of numbers then it makes the same process for the new area of numbers. But it the value is lower it makes the same with the lower area of numbers. And if none of these cases is true then it returns the max value (it could be the min value because they're the same at this point). But why gives that an StackOverflowError? I don't see why the programm can't end. Any help would be appreaciated. Thank you.

public class Starter {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    Starter s = new Starter();
    System.out.println(s.guessNumber(18, 1, 100));
}

public int guessNumber(int num, int min, int max) {
    int middle = (max - (min - 1)) / 2;
    if (num > middle) {
        guessNumber(num, middle + 1, max);
    } else if (num < middle) {
        guessNumber(num, min, middle);
    }
    return max;
}
}

Now I don't get an error anymore with this code:

public int guessNumber(int num, int min, int max) {
int middle = (max + min) / 2;
if (num > middle) {
    return guessNumber(num, middle + 1, max);
} else if (num < middle) {
    return guessNumber(num, min, middle);
}
return max;
}

But the number isn't correct. If i call it this way guessNumber(18, 1, 100) the expected output should be 18 but i get 19 . And if i call it this way guessNumber(34, 1, 100) then the ouput is 37

First of all, you forgot to return the value of the recursive calls.

Second of all, your calculation of middle is wrong. For example, if min is 10 and max is 20, your calculation will assign 5 to middle , instead of 15.

public int guessNumber(int num, int min, int max) {
    if (min == max) {
        return min;
    }
    int middle = (max + min) / 2;
    if (num > middle) {
        return guessNumber(num, middle + 1, max);
    } else {
        return guessNumber(num, min, middle);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM