2013-01-17 18 views
0

我正在写一个老虎机类,它生成3个随机数的3个数组,并检查所有数字是否匹配,如果是的话,他们被宣布为获胜者。我已经编写了另一个程序来运行1000台老虎机并计数获胜者。我面临的问题是它总是给我0个赢家。任何帮助?下面是每个代码:Java SlotMachine类

的SlotMachine类

import java.util.*; 

public class SlotMachine{ 

    private int[] row1 = new int[3]; 
    private int[] row2 = new int[3]; 
    private int[] row3 = new int[3]; 

    public SlotMachine() { 
     playMachine(); 
    } 

    public void playMachine() { 

     Random rand = new Random(); 

     for (int counter = 0; counter < 3; counter++) { 
      row1[counter] = rand.nextInt(10); 
     } 

     for (int counter = 0; counter < 3; counter++) { 
      row2[counter] = rand.nextInt(10); 
     } 

     for (int counter = 0; counter < 3; counter++) { 
      row3[counter] = rand.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; 
    } 
} 

赢奖计数器:

import java.util.*; 

public class Play1000SlotMachines { 

    public static void main(String[] args) { 
     SlotMachine slotMachine = new SlotMachine(); 
     int count = 0; 

     for (int i = 0; i < 1000; i++) { 
      if (slotMachine.isWinner() == true) { 
       count = count + 1; 
      } 
     } 

     System.out.println("From 1000 slot machines, " + count + " were winners."); 
    } 
} 
+2

你只玩一次。 – BevynQ

回答

1

你永远不会再卷老虎机。我也改变了方法的名称,以反映这个实现。如果您想玩1000台不同的老虎机,请将新老虎机的声明移至for循环。这将创建1000个不同的老虎机类实例,而不是下面的实现,其中创建一个老虎机的单个实例,然后再播放1000次。一个重要的区别。

public class PlaySlotMachine1000Times { 
    public static void main(String[] args) { 

    SlotMachine slotMachine = new SlotMachine(); 
    int count = 0; 

    for (int i = 0; i < 1000; i++) { 
     slotMachine.playMachine(); 
     if (slotMachine.isWinner()) 
     count++; 
    } 
    System.out.println("From 1000 slot machines, " + count + " were winners."); 
    } 
} 
+0

您还可以在'if'条件中省略'== true'并在'if'-body中写入'count ++;'。 – user3001

+0

好点,编辑反映。 –