每次出现菜单时,我如何使骰子不重新滚动:

当我按下菜单1选项时,就会发生循环,如何使值保持不变,直到我选择骰子重新滚动:

import java.io.InputStream;
import java.util.Scanner;

class RecordDice {
    public static void main(String[] args) {

        int dSides, Sides, Choice;
        int max = 0, min = 0;
        Scanner s = new Scanner(System. in );
        Scanner c = new Scanner(System. in );

        boolean keepgoing = true;

        System.out.println("How many sides should the dice have?");
        Sides = s.nextInt();
        if (Sides == 4 || Sides == 6 || Sides == 12 || Sides == 20 || Sides == 100) {

            while (keepgoing) {

                System.out.println("Please make a choice:\n" +
                    "1 - reroll the dice\n" +
                    "2 - get the value\n" +
                    "3 - show the maximum\n" +
                    "4 - show the minimum");

                Dice2 d = new Dice2(Sides);
                Choice = c.nextInt();
                int Value = d.getValue();

                if (Value > max) {
                    max = Value;
                }
                if (Value < min) {
                    min = Value;
                }


                if (min > max) {
                    max = min;
                }

                switch (Choice) {
                    case 1:

                        d.reroll();
                        break;
                    case 2:
                        System.out.println("The current value is " + Value);
                        break;
                    case 3:
                        System.out.println("The maximum is " + max);
                        break;
                    case 4:
                        System.out.println("The minimun is " + min);
                        break;
                }
            }
        }
    }
}

最佳答案

您的骰子似乎没有重新滚动。尽管我看不到类Dice2的外观,但我想您的问题是您在循环的每次迭代中都创建了一个新的Dice2。因此,您将失去对上一卷的参考。
将Dice2 d = new Dice2(Sides)放置在while循环之外。它可能看起来像这样:

Dice2 d = new Dice2(Sides);

while (keepgoing) {

    System.out.println("Please make a choice:\n" +
    "1 - reroll the dice\n" +
    "2 - get the value\n" +
    "3 - show the maximum\n" +
    "4 - show the minimum");

    Choice = c.nextInt();
    int Value = d.getValue();

    if(Value > max){
        max = Value;
    }
    ...


希望对您的问题有所帮助! (请注意,此解决方案假定您将Dice的roll值存储在Dice2对象中)

09-26 15:18