为什么我得到null

时间:2014-06-27 15:33:35

标签: java null

有些人可以帮我解决这个问题。当我尝试打印getCorrectAnswer时,它打印为null。我怎样才能获得正确的答案,以便打印出正确的答案。

public class Test1 {

    private String correctAnswer;

    public String getCorrectAnswer() {
        return correctAnswer;
    }

    public void setUpCorrectAnswer() {
        if (1 == 1) {
            correctAnswer = "a";
        } else {
            correctAnswer = "d";
        }
    }

    public static void main(String[] args) {
        Test1 a = new Test1();
        System.out.println(" Answer " + a.getCorrectAnswer());
    }
}

2 个答案:

答案 0 :(得分:0)

您没有调用setUpCorrectAnswer()。

    public static void main(String[] args) {
    Test1 a = new Test1();
    a.setUpCorrectAnswer();
    System.out.println(" Answer " + a.getCorrectAnswer());
}

答案 1 :(得分:0)

您需要使用setUpCorrectAnswer()方法设置值。

public static void main (String [] args) {
  Test1 a = new Test1();
  a.setUpCorrectAnswer(); // here
  System.out.println(" Answer " + a.getCorrectAnswer());
}