如何在java中重复添加变量?

时间:2015-03-16 02:11:31

标签: java

我有以下代码,目的是将骰子滚动10,000次然后添加所有这对骰子:

 package assignments;

    import java.util.Random;

    public class Dice {

        private int numbers;
        private static Random generator;

        public Dice() {
            generator = new Random();
            numbers = 0;    
        }

        public void Roll() {
            numbers = generator.nextInt(6) + 1;
        }

        public int getNumbers() {
            return numbers;
        }

    }

还有:

package assignments;

public class RollDice {

    public static void main(String[] args) {

        final int rollCount = 10000;

        Dice die1 = new Dice();
        Dice die2 = new Dice();

        int die1Number;
        int die2Number;

        int count = 0;

        int dieTotal = 0;

        for (count = 0; count < 10000; count++) {
            die1.Roll();
            die1Number = die1.getNumbers();

            die2.Roll();
            die2Number = die2.getNumbers();

            dieTotal = die1Number + die2Number;
            count++;
        }

        System.out.println(dieTotal);
    }
}

问题在于骰子实际上没有被滚动10,000次,或者只是每次循环通过时都会为骰子做一个新的输入。

有人可以帮我每次添加新的模具卷吗?

3 个答案:

答案 0 :(得分:1)

我改进了你的第二堂课代码。删除了冗余代码

package assignments;

public class RollDice {

    public static void main(String[] args) {

        final int rollCount = 10000;

        Dice die1 = new Dice();
        Dice die2 = new Dice();

        int die1Number;
        int die2Number;

        int dieTotal = 0;

        for (int count = 0; count < rollCount ; count++) {
            die1.Roll();
            die1Number = die1.getNumbers();

            die2.Roll();
            die2Number = die2.getNumbers();

            dieTotal += die1Number + die2Number; 
        }

        System.out.println(dieTotal);
    }
}

答案 1 :(得分:0)

您使用dieTotal运算符在每次迭代时覆盖=变量的值。使用dieTotal += (die1Number + die2Number),这与说dieTotal = dieTotal + die1Number + die2Number相同,dieTotal会添加{{1}}的旧值以及新的掷骰。

答案 2 :(得分:0)

您将count ++添加到for循环的底部。

For循环将自动计数,因此,通过这样做,您可以有效地将其数量减半,使其为5,000而不是10,000。 你也不需要指定int count = 0;在循环之外。

你可以删除它们并简单地用于(int count = 0; count&lt; 10000; count ++)。

你也想检查Jame,正如他所说,做dieTotal + =(die1Number + die2Number);或者其他东西。