简体   繁体   English

用Java循环...?

[英]Looping in Java…?

I'm having trouble looping this program. 我在循环该程序时遇到麻烦。 I believe everything in the private method is correct, however, I cannot get the main method right to create the loop. 我相信private方法中的所有内容都是正确的,但是,我无法正确地创建main方法来创建循环。 The code is below and a description of what it does is in the comments. 下面是代码,注释中有其功能说明。

Thanks. 谢谢。

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;
    }
}
  • Random should be initialized one time. 随机应初始化一次。 It may create the same results each time 每次可能会产生相同的结果
  • you private method is never called in the loop. 您的私有方法永远不会在循环中被调用。 Why? 为什么?
  • the profit is not defined in the mail method to store the profit returned by the private method 在mail方法中未定义利润来存储由private方法返回的利润

You should change: 您应该更改:

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

to something like: 像这样:

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

Please note: A method, except the constructor, should NOT be named like the class. 请注意:除构造函数外,方法的名称不应类似于类。 rename your method to something like "rollFatalFive()". 将您的方法重命名为“ rollFatalFive()”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM