Reputation: 69
I´m working on a Java-program in BlueJ, and I´m using a pseudorandom generator to generate a random number between a max number and a minimum number. I don´t get any syntax errors, but when i call the method it says it´s a null. Does anyone have any idea? I have imported the Random-class and it´s called randomizer in the constructor.
public void attackEnemy()
{
int damage = 0;
int max = 41;
int min = 20;
damage = randomizer.nextInt(max - min) + min;
health = health - damage;
}
Upvotes: 2
Views: 2840
Reputation: 4907
You needed to state that randomizer was infact a Random. It also looked like in your original code that you didn't quite complete the calculations. Take a look below:
public void attackEnemy(){
int max = 41;
int min = 20;
Random randomizer = new Random();
int damage = min + (max - min) * randomizer.nextInt();
health = health - damage;
}
I also think that the reason you're receiving a null output, is because you're not returning anything. So you could also display it as the following:
public int attackEnemy(){
int max = 41;
int min = 20;
Random randomizer = new Random();
int damage = min + (max - min) * randomizer.nextInt();
health = health - damage;
return health;
}
Upvotes: 0
Reputation: 45060
Initialize your randomizer
like this:-
randomizer = new Random(); // Without this, it'll throw a NPE
Upvotes: 2
Reputation: 236004
Did you do this?
randomizer = new Random();
The only value that can be null
in the snippet shown is the randomizer
object. You should instantiate it somewhere else in the class where is being used.
Upvotes: 3