2014-03-25 123 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++)