For my java class, I am suppose to create a SlotMachine class that generates 3 arrays of 3 random numbers and checks if all of the numbers match, if so they are declared a winner. I also have to create a another program to run 1000 slot machines and count the winners. The problem is every time I run the SlotMachine class and the main method, I get an exception error that I can't figure out how to fix.
The exception error:
Exception in thread "main" java.lang.NullPointerException
at SlotMachine.isWinner(SlotMachine.java:41)
at Play1000SlotMachines.main(Play1000SlotMachines.java:14)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
The SlotMachine class:
// import statements
import java.util.Random;
public class SlotMachine {
// fields
private int[] row1;
private int[] row2;
private int[] row3;
// methods
public SlotMachine(){
playMachine();
}
public void playMachine(){
Random random = new Random();
int row1[] = new int[3];
int row2[] = new int[3];
int row3[] = new int[3];
for (int i = 0; i < 3; i++) {
row1[i] = random.nextInt(10);
}
for (int i = 0; i < 3; i++) {
row2[i] = random.nextInt(10);
}
for (int i = 0; i < 3; i++) {
row3[i] = random.nextInt(10);
}
}
public boolean isWinner(){
if (row1[0] == row1[1]){
if (row1[0] == row1[2]){
return true;
}
}
if (row2[0] == row2[1]){
if (row2[0] == row2[2]){
return true;
}
}
if (row3[0] == row3[1]){
if (row3[0] == row3[2]){
return true;
}
}
return false;
}
}
The main method:
public class Play1000SlotMachines{
public static void main(String[] args){
// comment
SlotMachine slotMachine = new SlotMachine();
// comment
int count = 0;
// comment
for (int i = 0; i < 1000; i++){
slotMachine.playMachine();
if (slotMachine.isWinner())
count++;
}
// comment
System.out.println("From 1000 slot machines, " + count + " were winners");
}
}