当我点击一个按钮时,我试图使用来自 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)
按键方式
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);
}
类中涉及的对象
CoinTracker co = new CoinTracker();
RollProgress rpo = new RollProgress();
private Random dice;
private int rollProgressMA = rpo.rollProgress;
RollProgress 类的整数值
public int rollProgress = 1;
在此先感谢您尝试解决/解决方案。
最佳答案
私有(private)随机骰子;
在 dice.nextInt(rollProgressMA);
中使用它之前,我没有看到任何初始化 dice
变量的代码。
只需将声明更改为:
private Random dice = new Random();
关于java - 尝试在空对象引用上调用虚拟方法 'int java.util.Random.nextInt(int)' [Android],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26562162/