【问题标题】:How do I compare results from different loops with each other?如何将不同循环的结果相互比较?
【发布时间】:2020-07-04 03:00:59
【问题描述】:

我的问题是,使用我现在的代码,它会不断生成新的结果/骰子,但是说第 2 轮中的结果 2 与第 3 轮中的结果 1 相同,那么它也应该停止生成新结果。它现在不这样做。我怎么能调整 s.t.它会这样做吗?

int trials = 0;

for (int totalGames = 1; totalGames <= 3; totalGames++ ) {

    int result1, result2;

    // simulating dice rolls
    do {
        result1 = (int) (Math.random() * 6) + 1;
        result2 = (int) (Math.random() * 6) + 1;
        trials++;
        System.out.println(result1);
        System.out.println(result2);

    }
    while (result1 != result2);

【问题讨论】:

    标签: java loops do-while


    【解决方案1】:

    您必须跟踪某种集合中的每个结果,然后检查结果是否已包含在该集合中:

    /**
     * @return The amount of trials it took to get two matching numbers.
     */
    public static int roleDice() {
        int trials = 0;
        HashSet<Integer> seenResults = new HashSet<Integer>();
    
        for (int totalGames = 1; totalGames <= 3; totalGames++) {
            int result1, result2;
    
            do {
                result1 = (int) (Math.random() * 6) + 1;
                result2 = (int) (Math.random() * 6) + 1;
                System.out.println(result1);
                System.out.println(result2);
    
                // Set.add(...) returns false if the value is already contained
                if (!(seenResults.add(result1) && seenResults.add(result2)))
                    return trials;
    
                trials++;
            } while (result1 != result2);
        }
    
        return trials;
    }
    
    public static void main(String[] args) {
        int trials = roleDice();
    }
    

    【讨论】:

    • 使用Set 会更好
    • 感谢您的回复!我正在尝试生成(骰子的)随机数,直到两个连续的随机数相同,然后循环应该结束。
    • @GwenLS 两者 while 和 for 循环?
    • @Schred for 循环是我不想做“实验”的次数。 while循环是计算两个连续随机生成的数字相同之前所进行的试验次数=实验。
    • 如果有两个相同的数字,你想怎么办?
    【解决方案2】:

    通过这种方式,您可以在每次迭代中检查任何先前的 result1 值是否与当前的 result2 值匹配,以及是否有任何先前的 result2 值与当前的 result1 值匹配,直到条件评估为真并且您退出 while 循环。

    int trials = 0;
    for (int totalGames = 1; totalGames <= 3; totalGames++) {
        Set<Integer> result1Set = new HashSet<>();
        Set<Integer> result2Set = new HashSet<>();
        while (true) {
            trials++;
            int result1 = (int) (Math.random() * 6) + 1;
            int result2 = (int) (Math.random() * 6) + 1;
            if (result1Set.contains(result2) || result2Set.contains(result1)) {
                break;
            }
            result1Set.add(result1);
            result2Set.add(result2);
            System.out.println(result1);
            System.out.println(result2);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-17
      • 1970-01-01
      • 2019-01-28
      • 2012-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-19
      相关资源
      最近更新 更多