Construct0r Construct0r - 21 days ago 5
Java Question

Arrays and Null Pointer Exception

I'm trying to make a lottery game. I understand that there is an easier or quicker way to do this, but I'm trying to use all the tools I have learned. I've split things up in methods (getting user input, setting random value and etc..) When I run the code, I get a

java.lang.NullPointerException
.

public class LotteryGame {

private int[] numbers;
private int value;
private boolean winner = false;

public void setWinningNumber() {
Random rand = new Random();
// Winning number is b/w 1 and 10
this.value = rand.nextInt(11);
System.out.println("The winning number is: " + value);
}

public void getNumbers() {

Scanner scan = new Scanner(System.in);

// Hold numbers in lottery
int[] numbers = new int[5];

// Get user input and store in array of 5 elements
for (int i = 0; i < numbers.length; i++) {
System.out.println("Enter number: ");
numbers[i] = scan.nextInt();
}

for(int num : numbers) {
System.out.println(num);
}
}

public boolean isWinner(){
for(int j = 0; j < numbers.length; j++){
if(numbers[j] == value){
System.out.println("Congratulations you won!");
this.winner = true;
}
else {
System.out.println("Sorry you lost. Try again.");
this.winner = false;
}
}

return this.winner;
}


The problem is in the isWinner() method. I've already passed in user values into the array from getNumbers() method, but why don't those values transfer over to the isWinner() method?

Answer

The problem is that in your getNumbers() method you make a variable called numbers, which shadows the field this.numbers declared in the class. This means that the field this.numbers remains null even after you are out of getNumbers()

Remove int[] from the declaration to fix this problem:

numbers = new int[5];

Now the declaration of a local variable became an assignment of a field.