As it stands, if your condition is false in your for loop, then it will be false at ALL iterations, and you're just wasting computation time. The if-statement on it's own will suffice.
public boolean addCompetitor(Competitor competitor) {
if(numberOfCompetitors < MAX_COMPETITORS)
{
competitors[numberOfCompetitors++] = competitor;
return true;
}
return false;
}
You know how many competitors you have entered so far. You need not a loop, just check if you've added too many directly.
A loop would be necessary if you didn't already save how many competitors you've added like this(this requires that no legitimate entries can be null, or it will be overwritten):
public boolean addCompetitor(Competitor competitor)
{
for(int i = 0 ; i < competitors.length ; i++)
{
if(competitors[i]==null)
{
competitors[i] = competitor;
return true;
}
}
return false;
}
This approach will take longer the more competitors you've added (O(n)), while the other approach always takes the same amount of time (O(1))
Addressing the error on the new edit
for(int i=0; i<competitors.length; i++){
You're looping through your whole competitors array, which may not have competitors yet.
Try changing it to
for(int i=0; i<numberOfCompetitors; i++){
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…