Qwertywasd
Qwertywasd

Reputation: 45

Exiting a non void method? (Java)

I was wonder how you would go about exiting a method early. If this was a void type, I would just do "return", however since this is an int type, it wants me to return an integer. How do I return to main without returning any integers. Thanks.

public static int binarysearch(String[] myArray, String target, int first, int last)
{
    int index;

    if  (first > last)
    {
        index = -1;
        System.out.println("That is not in the array");
        // Return to main here
    }

Upvotes: 1

Views: 4828

Answers (2)

wjl
wjl

Reputation: 7351

You can't return from a method without a return value, in the traditional sense.

You can either return -1; and declare in your documentation that -1 represents a failed search, or you can throw an exception. If you throw an exception, though, you'll need to catch it. You can read more about that in the linked article.

Upvotes: 4

Phill Healey
Phill Healey

Reputation: 3180

A couple of options.... 1. break; 2. return a value that you know would not be returned from a valid result. Eg 99999999 or -34

Those would be simple choices....

Edit Of course break would only exit the loop. So youd still need to return a known value.

Upvotes: 0

Related Questions