2014-03-25 92 views
-2
//creates SevenTally class 
public class SevenTally{ 

    private int count; 

    public SevenTally(int diceCount){ 
     this.count = diceCount; 
    } 

    //creates experiment method 
    public boolean experiment(){ 
     int winCount = 0; 
     //creates array of dice rolled according to input 
     int[] diceRolls = new int[count]; 
     //assigns random value from 1 to 6 to each array value 
     for(int x = 0; x < diceRolls.length; x++) { 
      diceRolls[x] = (1 + (int)(6 * Math.random())); 
      for(int n = 0; n < diceRolls.length; n++) { 
       for(int m = n + 1; m < n; m++){ 
        //checks for two dice in the total rolls that sum to 7 
        if (diceRolls[n] + diceRolls[m] == 7) 
         winCount++; 
       } 
      } 
     } 
     if (winCount > 0) 
      return true; 
     else 
      return false; 
    } 
} 

看起来问题在于数组for循环。我测试了代码的那一部分,并且它正在向我的数组中正确地输入值,但是当我将所有东西放在一起时,我认为在退出循环后数组留空或清空。为什么输出总是0.0?

这是类驱动程序:

import java.util.Scanner; 

public class SevenDriver{  

    public static void main(String[] args){  
     System.out.println("Enter number of dice to toss");  
     Scanner s = new Scanner(System.in);  
     int diceCount = s.nextInt(); 
     SevenTally t = new SevenTally(diceCount); 
     int experiments = 1000000; 
     int wins = 0; 

     for(int j = 0; j < experiments; j++) 
      if(t.experiment()) wins++; 

     System.out.println((double)wins/experiments); 
    } 
} 
+1

你没有解释你想要做什么,你只是问人们为什么输出是错误的。请添加一个算法的解释,以及某种测试场景的预期结果。 – bitoiu

回答

2

你写

for(int m = n + 1; m < n; m++) 

m开始在n+1和循环应该同时m<n运行,那么有没有很多工作要做。这一个应该工作:

for(int m = n + 1; m < diceRolls.length; m++)