使用"Gambler-code"进行故障排除



我在学校做一个项目,如果我们应该模拟下注方案,我们就可以使用此代码。

http://introcs.cs.cs.princeton.edu/java/13flow/gambler.java.html

但是,我们的任务是更改此代码,以便每个下注的下注都应该打印出我们在该下注之后的每一美元的" *"。

因此,例如,如果我们在第一个下注之后赢得1美元,并且我们以5美元的股份开始,那么该程序应打印6"*",然后在下一个下注,反之亦然。p>我尝试了不同的事情,但似乎可以使它正常工作,因此我问你们在这里寻求一些建议/帮助。

这就是我到目前为止提出的;

public class GamblerStars {
    public static void main(String[] args) {
        int stake = Integer.parseInt(args[0]); // gambler's stating bankroll
        int goal = Integer.parseInt(args[1]); // gambler's desired bankroll
        int trials = Integer.parseInt(args[2]); // number of trials to perform
        int bets = 0; // total number of bets made
        int wins = 0; // total number of games won
        // repeat trials times
        for (int t = 0; t < trials; t++) {
            int cash = stake;
            int star = 0;
            while (cash > 0 && cash < goal) {
                bets++;
                if (Math.random() < 0.5) {
                    cash++; // win $1
                    while (star <= cash) {
                        star++;
                        System.out.print("*");
                    }
                } else {
                    cash--; // lose $1
                    while (star <= cash) {
                        star--;
                        System.out.print("*");
                    }
                }
                System.out.println("");
            }
            if (cash == goal)
                wins++; // did gambler go achieve desired goal?
        }
        System.out.println(wins);
    }
}

我会更改您的块:

    // it's always a good idea to parametize your conditions
    while ((cash > 0) && (cash < goal)) {
        bets++;
        if (Math.random() < 0.5) {
            cash++; // win $1
        }
        else {    // move the else up here, so it's parallel to the win
            cash--; // lose $1
        }
        // you only need one block to print the stars, not two
        while (star <= cash) {
                star++;
                System.out.print("*");
        }
        // you don't need to use a parameter to just print a newline            
        System.out.println();
    }

至少应该帮助您发现问题。

最新更新