Attempt to invoke virtual method 'int java.uti

2019-07-04 11:26发布

问题:

I'm trying to use the rng from java when I click a button but each time I click it the program crashes and gives me the following error:

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)

Button Press Method

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);
}

Objects involved in class

CoinTracker co = new CoinTracker();
RollProgress rpo = new RollProgress();
private Random dice;
private int rollProgressMA = rpo.rollProgress;

Int value from RollProgress class

public int rollProgress = 1;

Thanks in advance for any attempts at solving/solutions.

回答1:

private Random dice;

I don't see any code that initializes the dice variable before you use it in dice.nextInt(rollProgressMA);.

Just change the declaration to :

private Random dice = new Random();