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

时间:2011-07-18 07:05:23

标签: java loops flow

我正在为Java类编写一个简单的craps模拟器,由于某些原因,它无法正常运行。它应该用“点”跟踪损失并用“点”获胜,但由于某种原因,这些值每次都倾向于1或0。第一次滚动的损失和胜利似乎正在发挥作用。想知道是否有一个新鲜的眼睛的人可以弄清楚我搞砸了哪里。谢谢!

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");
  }
}

2 个答案:

答案 0 :(得分:2)

通过调试器运行它,或者使用System.out.println并查看逻辑失败的位置。这是家庭作业吗?

答案 1 :(得分:1)

您的问题是gameover标志。你总是在内循环结束时将它设置为false,这将使它永远运行。