I cannot figure out why Ecplise won't let me execute the 3rd statement (i ) in my for loop due to it being "Dead Code", which I don't even know what that means. Anyone know why?
public int getIdx(int studID) {
for (int i = 0; i < classSize; i ) {
if (this.StudID[i] == studID) {
return i;
}
break;
}
return -1;
}
CodePudding user response:
This is because your loop breaks after first iteration.
public int getIdx(int studID) {
for (int i = 0; i < classSize; i ) {
if (this.StudID[i] == studID) {
return i;
}
break; // <-- because of this, second iteration is never executed
}
return -1;
}
Did you mean to place break
under the if
condition? If so, actually, you don't need it since return
already breaks a loop.
It seems like you're trying to do lineary search. Here is how it may look like.
public int getIdx(int studID) {
for (int i = 0; i < classSize; i ) {
if (this.StudID[i] == studID) {
return i;
}
}
return -1;
}
CodePudding user response:
The dead code pretty much means that there will be lines of code that are never going to run. Such as having always true in an if-else statement. Your loop will break after the first iteration, so it is pointless to have a for-loop if the line of code is gonna execute only once.
Removing the break;
should do the trick! You don't need to stop the loop because it already does when you return the i
variable.