Which I believe means that I need a return statement at the end of my while loop. But in the examples in my text book, and all the examples of binary search I've found online, there is not a return statement at the end of the while loop.
It has less to do with the end of your while loop and more to do with the fact that the compiler wants an int return because your method calls for a return of int. What if, for some reason, the logic in the while loop is false? None of the if else logic would ever be checked and that leaves a method with no return value. You have to have a return value outside of the while loop and MORE importantly within the direct reach of the binarySearch() method.
To make it really simple, the reason your code doesn't work is the same reason this wouldn't...
It doesn't matter if the while loop was true or false, the compiler would have an error. Can you blame it?
Just looking at your code, I wanted to share this video that shed some light to me. I am a new programmer, but I care very much about code readability ability to extend and I spend a great deal of time making this right. I believe it will pay me more in the future, by a lot!
Scott M Summers wrote:I am having trouble with the Binary search for a string array. When my code calls binarySearch (line #43), I get an error:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - missing return statement
Java Result: 1
My example above is better like this. Otherwise while(false) makes an unreachable statement even if you make a return value outside of the while. But either way it it needs a return value and if if logic is used then it needs a return for either way the logic goes. But again, like I said, I am kinda new. I was just trying to make a point.