1

我基于给定的 GUI 实现了一个类,我试图覆盖 tostring() 以在 GUI 上显示信息,但我无法让它正常工作。

图形用户界面代码

private void updateDisplay() {
    try {
        if (game.isAccepted()) {
            String str = "Selected Applicant:\n\n"
                    + currentApplicant.toString() + "\n\nwas ";
            if (game.isBestApplicant()) {
                str += "the BEST.  You Win!";
            } else {
                str += "not the best available.  You Lose.\n\nBest applicant was: \n\n"
                        + game.getBestApplicant();
            }
            display.setText(str);
            showNewGameControls();
        } else {
            display.setText("Current applicant is:\n\n"
                    + currentApplicant.toString()
                    + "\n\nDo you wish to accept or reject?");
            showCurrentGameControls();
        }
    } catch (HiringException e) {
        display.setText(e.getMessage());
    } catch (Exception e) {
        display.setText("Unandled Exception: " + e.toString());
        throw new RuntimeException(e);
    }
}

对于我正在实现的类,我编写了以下方法

public String tostring(){
  return currentApplicant;
}
4

1 回答 1

3

您需要使用toString, not tostring,因为 Java 区分大小写。因此:

public String toString()

从技术上讲,tostring 与 Java 中的 toString 不同。小心拼写。如果您的编辑器支持它,请使用@Override注释。@Override注释可防止您无法覆盖正确的方法。

于 2013-04-15T06:43:13.587 回答