简体   繁体   English

Java 循环错误 - 需要新鲜的眼睛

[英]Java Looping Error - Need fresh eyes

I am writing a simple craps simulator for Java class and for some reason, it is having trouble running correctly.我正在为 Java class 编写一个简单的掷骰子模拟器,由于某种原因,它无法正常运行。 It is supposed to keep track of losses with "point" and wins with "point" but for some reason, those values tend to be 1 or 0 everytime.它应该用“point”跟踪损失并用“point”获胜,但由于某种原因,这些值每次都倾向于为 1 或 0。 The losses and wins on first roll seem to be working.第一轮的输赢似乎正在发挥作用。 Wondering if someone with a fresh set of eyes can figure out where I messed up.想知道是否有一双新眼睛的人可以弄清楚我在哪里搞砸了。 Thank you!谢谢!

import java.util.Scanner;
import java.util.Random;

class CrapsSimulator {

  public static void main(String[] args) {

    // Set up values we will use
    int lossfirstroll = 0;
    int winfirstroll = 0;
    int losswithpoint = 0;
    int winwithpoint = 0;

    boolean gameover = false;
    int point = 0;

    // Loop through a craps game 100 times
    for (int i = 0; i < 100; i++) {

        // First roll -- random number within 2-12
        Random rand = new Random();
        int random = rand.nextInt(11) + 2;

        // Win on first roll
        if (random == 7 || random == 11) {
            winfirstroll++;
            gameover = true;
        } // Loss on first roll
        else if (random == 2 || random == 3 || random == 12) {
            lossfirstroll++;
            gameover = true;
        } else // Player has "point"
        {
            point = random;
        }

        // Check to make sure the game hasn't ended already
        while (gameover == false) {
            // Reroll the dice
            random = rand.nextInt(11) + 2;

            // Check to see if player has won
            if (random == point) {
                winwithpoint++;
                gameover = true;
            }

            // Or if the player has lost
            if (random == 7) {
                losswithpoint++;
                gameover = true;
            }

            // Otherwise, keep playing
            gameover = false;
        }
    }

    // Output the final statistics
    System.out.println("Final Statistics\n");
    System.out.println("Games played: 100\n");
    System.out.println("Wins on first roll: " + winfirstroll + "\n");
    System.out.println("Losses on first roll: " + lossfirstroll + "\n");
    System.out.println("Wins with point: " + winwithpoint + "\n");
    System.out.println("Losses with point: " + losswithpoint + "\n");
  }
}

either run it through a debugger, or sprinkle System.out.println and see where your logic is failing.要么通过调试器运行它,要么撒上System.out.println看看你的逻辑在哪里失败。 Is this homework?这是作业吗?

Your problem is the gameover flag.你的问题是gameover标志。 You are always settings it to false again at the end of the inner loop, this will make it run forever.您总是在内部循环结束时再次将其设置为false ,这将使其永远运行。

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

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