对于我的java类,我想创建一个SlotMachine类,它生成3个3个随机数的数组,并检查所有数字是否匹配,如果是,则将它们声明为胜利者。我还必须创建另一个程序来运行1000个老虎机并计算获胜者。问题是每次我运行SlotMachine类和main方法时,都会出现异常错误,我无法弄清楚如何修复。
异常错误:
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)
SlotMachine类:
// 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;
}
}
主要方法:
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");
}
}