【问题标题】:Make Math.Random loop until specific number is reached进行 Math.Random 循环,直到达到特定数字
【发布时间】:2014-12-15 23:57:16
【问题描述】:

我正在尝试制作一个“掷两个骰子”并组合数字的程序,并且需要继续运行,直到达到特定数字 7 或 11,但每次运行它都会一直运行下去。

double total = 0;
while (total != 7 || total != 11) {
    DecimalFormat x = new DecimalFormat("#");
    double dice1 = Math.random() * 6 + 1;
    double dice2 = Math.random() * 6 + 1;
    double total = (dice1 + dice2);
    System.out.println("Dice 1: " + x.format(dice1) + " Dice 2: " + x.format(dice2) + " Total: " + x.format(total));

    }

我认为这是因为 int total 设置为 0 并且没有从循环中获取总数,但是我该如何解决这个问题?

【问题讨论】:

  • 这段代码应该有编译错误:变量total已经在这个范围内定义了。
  • 在这种情况下,使用调试器单步执行会对您有好处!

标签: java math random dice


【解决方案1】:

这是因为您隐藏total 并且您需要测试逻辑与(非或)。我也更喜欢使用RandomnextInt(int) 之类的

int total = 0; // <-- don't shadow me.
Random rand = new Random(); 
while (total != 7 && total != 11) {
  int dice1 = rand.nextInt(6) + 1; // <-- using rand.
  int dice2 = rand.nextInt(6) + 1;
  total = (dice1 + dice2); // <-- no double.
  System.out.printf("Dice 1: %d Dice 2: %d Total: %d%n", dice1, dice2, total);
}

【讨论】:

  • 非常感谢,这非常有效。我不知道为什么我使用双精度,我猜双精度时它是一个绝对值?
  • 不,你在隐藏(或隐藏)total。基本上,循环中的total 是一个名为total 的不同变量。
  • @TajMelic 当您使用double 时,它会生成带有小数的数字。总和永远不会完全等于 7 或 11,即使你解决了阴影问题和逻辑 OR 问题。
  • @ElliottFrisch 感谢您清除此问题。现在更有意义了。这也可能是我不得不使用 DecimalFormat 来摆脱分数的原因。
  • @TajMelic 除了其他各种修复之外,您可能应该将 DecimalFormat 移到循环之外。
【解决方案2】:

您需要 AND 而不是 OR。并用 int 试试:

int total = 0;
    while (total != 7 && total != 11) {
        Random rand = new Random();
        int dice1 =  rand.nextInt((6 - 1) + 1) + 1;
        int dice2 =  rand.nextInt((6 - 1) + 1) + 1;
        total = (dice1 + dice2);
        System.out.println("Dice 1: " + dice1 + " Dice 2: " +dice2 + " Total: " + total);

【讨论】:

    【解决方案3】:

    您的while 循环逻辑不正确。总数将始终不是7 或不是11。你想用“和”代替,使用&amp;&amp;。改变

    while (total != 7 || total != 11) {
    

    while (total != 7 && total != 11) {
    

    另外,我不知道任何骰子会产生非整数,所以我会将结果转换为int,并将dice1dice2total 声明为ints。

    【讨论】:

      猜你喜欢
      • 2014-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多