在Java中循环....?

时间:2016-04-06 21:19:39

标签: java loops

我无法循环播放此程序。我相信私有方法中的所有内容都是正确的,但是,我无法获得创建循环的主方法。代码如下,并在评论中描述了它的作用。

感谢。

import java.util.Random;

/**
 * This program rolls the dice three times and the profit is the sum of the face
 * values that are obtained. Fives do not count and no roll after a five counts.
 * The program will be run 1 million times and the results will be averaged
 *
 * @author --
 */
public class FatalFives {

    public static void main(String[] args) {
        final int TRIALS = 1000000;
        int count = 0;

        while (count < TRIALS) {
            count++;
        }

        double avg = (double) profit / TRIALS;
        System.out.println("Your average winnings are: $" + avg);
    }

    private static int FatalFive() {
        Random rand = new Random();

        int profit = 0;

        int die1 = 1 + rand.nextInt(6);
        int die2 = 1 + rand.nextInt(6);
        int die3 = 1 + rand.nextInt(6);

        if (die1 == 5) {
            //System.out.println("You're unlucky, no profit");
            profit = 0;
        } else if (die1 != 5 && die2 == 5) {
            //System.out.println("Congrats! You won $" + die1);
            profit = (die1);
        } else if (die3 == 5) {
            //System.out.println("Congrats! You won $" + die1 + die2);
            profit = (die1 + die2);
        } else if (die1 != 5 && die2 != 5 && die3 != 5) {
            //System.out.println("Congrats! You won $" + (die1 + die2 + die3));
            profit = (die1 + die2 + die3);
        }
        return profit;
    }
}

1 个答案:

答案 0 :(得分:0)

  • 随机应初始化一次。它可能每次创建相同的结果
  • 你永远不会在循环中调用私有方法。为什么?
  • 利润未在邮件方法中定义,以存储私有方法返回的利润

你应该改变:

    while (count < TRIALS) {
        count++;
    }

类似于:

    long profit = 0;
    while (count < TRIALS) {
        profit += FatalFive();
        count++;
    }

请注意:除了构造函数之外,方法不应该像类一样命名。将您的方法重命名为&#34; rollFatalFive()&#34;。