public class GameEntry {
private String name;
private int score;
public GameEntry(String n, int s){
name = n;
score = s;
}
public String getName(){
return name;
}
public int getScore(){
return score;
}
public String toString(){
return "(" + name + ", "+ score + ")";
}
}
public class Scoreboard {
private int numEntries = 0;
public GameEntry[] board;
public Scoreboard(int capacity){
board = new GameEntry[capacity];
}
**public void add(GameEntry e){**
//System.out.println(board[numEntries - 1].getScore());
int newScore = e.getScore();
//Is the new entry really a high score
//*****This is the line i refer to as******
if (numEntries < board.length || newScore > board[numEntries - 1].getScore()) {
if (numEntries<board.length) {
numEntries++;
}
//shift any lower scores rightward to make room for the new entry
int j = numEntries - 1;
while(j>0 && board[j-1].getScore()<newScore){
board[j] = board[j-1]; //shift entry from j-1 to j
j--; // and decrement j
}
board[j] = e; // when done add a new entry
}
}
}
I would like to draw your attention inside the Scoreboard class, to its add method.
My question is why this code does not fail.
The first time the add method runs, the numEntries is equal to 0. So inside the if statement the board[numEntries - 1].getScore should get an IndexOutOfBounds.
When i put it before the if i get the proper exception. Does the if catch the exception?
I have printed the value of (numEntries - 1) and i get -1. But yet inside the if ot does not seem to bother it.
The line i refer to is inside the add method the first if.
if (numEntries < board.length || newScore > board[numEntries - 1].getScore())