0
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?

1
  • 2
    You could rename y to index. Commented May 20, 2013 at 10:20

5 Answers 5

8

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);
}
Sign up to request clarification or add additional context in comments.

Comments

5

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);
}

Comments

2

You can return directly:

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

3 Comments

isn't it y > -1 or y >= 0, since Java starts indexing from 0
Indeed, forgot the '=' signal from asker's example
@Felype You can edit and correct your answer by clicking on the edit link just below your answer. I've done it for you.
1

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

Comments

0

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 .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.