尝试在空对象引用上调用虚拟方法''

时间:2018-11-22 20:01:16

标签: java

我收到此错误“试图在空对象引用上调用虚拟方法'java.lang.String eecs1022.caps.Game.qa()'”

我只想知道为什么我会收到此错误以及如何解决该错误。

游戏对象返回一个字符串,但是由于某种原因它说它是一个空对象。这是我的主班和游戏课。

主要:

if ($object->state === 'complete') {
  $object->removeClass('highlighted');
} else {
  $object->addClass('highlighted');
}

}

游戏:

private Game game;
private String question = "";
private String answer = "";
private int score = 1;
private int qNum = 1;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ask();
    }


public void ask(){

    String apple = game.qa();
    int indexanswer = apple.indexOf("\n");
    answer = apple.substring(indexanswer);
    question = apple.substring(0,indexanswer);

    ((TextView)findViewById(R.id.question)).setText(question);

}

public void onDone (View v){

    if (qNum == 10){
        finish();
    }

    String answerinput = ((EditText)findViewById(R.id.answer)).toString();

    if (answer.equalsIgnoreCase(answerinput)){
        score++;
    }

    String oldlog = ((TextView)findViewById(R.id.log)).toString();
    String a = oldlog + "\n" + "Q# " + qNum + ": " + question + "\n" + "Your answer" + answerinput.toUpperCase() + "\n" + "Correct Answer: " + answer + "\n";
    ((TextView)findViewById(R.id.log)).setText(a);

    qNum++;
    String orange = "SCORE = " + score;
    String banana = "Q# " + qNum;

    ((TextView)findViewById(R.id.score)).setText(orange);
    ((TextView)findViewById(R.id.qNum)).setText(banana);

    ask();
}

}

感谢您的帮助!

1 个答案:

答案 0 :(得分:-1)

这样做: private Game game;

声明变量game,但实际上并没有初始化。这告诉编译器您将使用game来引用类型为Game的变量。但是,您实际上并没有为game赋值。这就是gamenull的原因。

要初始化game,您应该这样做: private Game game = new Game();