0

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

Orell Buehler
  • 116
  • 2
  • 9
  • as a sidenode, you want to `return guessNumber(...)` when you are calling it recursivly – SomeJavaGuy Jan 06 '16 at 07:56
  • Use a debugger Luke. – Stephen C Jan 06 '16 at 07:57
  • additionally you should include some sample input and your expected output in your question. This would make it more understandable for us to help you. – SomeJavaGuy Jan 06 '16 at 08:01
  • 1
    Possible duplicate of [What is a debugger and how can it help me diagnose problems](http://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Raedwald Jan 06 '16 at 08:03

1 Answers1

2

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);
    }
}
Eran
  • 387,369
  • 54
  • 702
  • 768
  • @PhamTrung You are right. I forgot that 1 is added to middle in this case. I'll review my answer and edit. Thanks. – Eran Jan 06 '16 at 08:14