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

Jua*_*uan 3 java random android nullreferenceexception

我点击按钮时尝试使用java中的rng,但每次单击它时程序崩溃并给出以下错误:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.Random.nextInt(int)' on a null object reference
at me.test.first.MainActivity.onGenPress(MainActivity.java:25)
Run Code Online (Sandbox Code Playgroud)

按钮按键方法

public void onGenPress(View v){
        TextView tv = (TextView) findViewById(R.string.copper);
        int number = 1 + dice.nextInt(rollProgressMA);
        co.copper += number;
        tv.setText("Copper: " + co.copper + " + " + number);
}
Run Code Online (Sandbox Code Playgroud)

课堂上涉及的对象

CoinTracker co = new CoinTracker();
RollProgress rpo = new RollProgress();
private Random dice;
private int rollProgressMA = rpo.rollProgress;
Run Code Online (Sandbox Code Playgroud)

RollProgress类的Int值

public int rollProgress = 1;
Run Code Online (Sandbox Code Playgroud)

提前感谢任何解决/解决方案的尝试.

Era*_*ran 7

private Random dice;

dice在使用变量之前,我没有看到任何初始化变量的代码dice.nextInt(rollProgressMA);.

只需将声明更改为:

private Random dice = new Random();