尝试在空对象引用上调用虚方法'int java.util.Random.nextInt(int)'

时间:2016-10-09 19:40:05

标签: java android random

问题确实存在问题:Attempt to invoke virtual method 'int java.util.Random.nextInt(int)' on a null object reference [Android]。但是我已经用Random实例化了Random变量,但它仍然不起作用。谁知道为什么?

label.frame.size.width / 2

按要求进行Stacktrace:

.
.
.
import java.util.Random;

public class game_page extends AppCompatActivity {

    private TextView gameProblem;
    private int leftNumber;
    private int rightNumber;
    private EditText solution;
    private String operator;
    private int sum;

    private Random r = new Random();

    private int difficulty;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game_page);
        gameProblem = (TextView)findViewById(R.id.game_problem);
        solution = (EditText)findViewById(R.id.solution);

        setDifficulty();
        newProblem();
    }

    //1 = easy
    private void setDifficulty() {
        this.difficulty = 1;
    }

    private void newProblem() {
        if(difficulty == 1){
            leftNumber = r.nextInt(0) + 10;
            rightNumber = r.nextInt(0) + 10;
            operator = "+";
            sum = Integer.parseInt(leftNumber + operator + rightNumber);
            gameProblem.setText(leftNumber + operator + rightNumber + "=");
        }
    }
}

0 个答案:

没有答案