//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;
}
}
似乎问题在于循环数组。我只测试了代码的那一部分,它正确地将值输入到我的数组中,但是当我将整个事物放在一起时,我认为数组在退出循环后保持为空或清空。
这是类驱动程序:
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);
}
}
答案 0 :(得分:2)
你写了
for(int m = n + 1; m < n; m++)
当m
从n+1
开始,并且循环应该在m<n
时运行时,那就没什么可做的了。这应该工作:
for(int m = n + 1; m < diceRolls.length; m++)