James Oliver
James Oliver

Reputation: 19

Taking integer arrays

boolean isValidIndex (int [] x, int y) {
    if((y>=0) && (y<x.length)) {
        return true;
    }
    else {
        return false;

    }
}

Write a method called isValidIndex() that takes an array of integers and an index, and returns true if the index is valid for the array. For example, if the array had 10 elements then isValidIndex(array, 9) would return True,but isValidIndex(array, 10) would return False,as would isValidIndex(array, -1).

Here is my code. It works but apparently it can just be one statement. How can I do that?

Upvotes: 0

Views: 205

Answers (5)

Felype
Felype

Reputation: 3136

You can return directly:

return (y >= 0 && y < x.length);

Upvotes: 2

Lakshmi
Lakshmi

Reputation: 2294

Make your function as

boolean isValidIndex (int [] x, int y) {

return ((y>=0) && (y<x.length));

}

the following will evaluate to true or false and the same can be returned .

Upvotes: 0

Keppil
Keppil

Reputation: 46239

Anything on the format if <expr> then true else false, can always be shortened to just <expr>. So, in your case:

boolean isValidIndex (int [] x, int y) {
    return (y >= 0) && (y < x.length);
}

Upvotes: 5

Tony Hopkinson
Tony Hopkinson

Reputation: 20330

return ( y >= 0) && (y < x.length);

Upvotes: 1

assylias
assylias

Reputation: 328893

The value of this expression: ((y >= 0) && (y < x.length)) is a boolean, so you can use it directly like this:

boolean isValidIndex (int [] x, int y) {
    return (y >= 0) && (y < x.length);
}

Upvotes: 8

Related Questions