Trying to return true if a sub array exists at given index


Joined
Mar 4, 2021
Messages
1
Reaction score
0
Hi, I am trying to return true if a sub-array exists at given index (idx), false otherwise. For example:
if idx = -1, return false since data[-1] is out of bounds
* if idx = 0, return true since data[0] refers to the first sub-array
* if idx = 1, return true since data[1] refers to the second sub-array
* ...
* if idx = data.length - 1, return true since data[data.length - 1] refers to the last sub-array
* if idx = data.length, return false since data[data.length] is out of bounds
*/

I have attempted the question but cannot seem to past the tests on eclipse. I am wondering what I am doing wrong?

public boolean isValidSubsetIndex(int idx) {

if(idx <= -1 || idx == data.length - 1 ) {
return true;
}else {
return false;
}
}
 
Ad

Advertisements

Joined
Mar 3, 2021
Messages
28
Reaction score
6
We've got a couple parts to unpack here. By the function name, we're returning true if the index is valid. So, the top part of your if block, which is returning true, should be checking if idx is above or equal to zero and less than or equal to `data.length - 1` (the latter of which can be simplified to less than data.length. Conversely, you could check for invalid cases instead, which might be a little more clear, depending on your context. In your example, you're checking for less than or equal to -1, which should be invalid. The other check, equal to one less than the data length, is a valid index, though, so it's unclear which direction you were heading.

Java:
if (idx >= 0 && idx <= data.length - 1){
    return true;
}

or

Java:
if (idx >= 0 && idx < data.length){
    return true;
}

or

Java:
if (idx < 0 || idx >= data.length){
    return false;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top