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
        }
    }
}


我想在Scoreboard类中吸引您注意它的add方法。

我的问题是为什么这段代码不会失败。

第一次运行add方法时,numEntries等于0。因此,在if语句中,board [numEntries-1] .getScore应该获得IndexOutOfBounds。

当我把它放在如果我得到适当的例外之前。 if是否捕获异常?

我已经打印了(numEntries-1)的值,我得到-1。但是在if ot内部似乎并不打扰它。

我指的是第一个if的add方法内部。

if (numEntries < board.length || newScore > board[numEntries - 1].getScore())

最佳答案

简单答案:逻辑或短路评估。

当条件的第一部分(即numEntries < board.length)评估为true时,根本不评估||之后的第二部分。

10-07 13:36