Reputation: 19
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
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
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
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