【问题标题】:I'm trying to randomise four variables but nothing seems to happen我正在尝试随机化四个变量,但似乎什么也没发生
【发布时间】:2021-06-23 19:05:47
【问题描述】:

所以我试图在显示锦标赛比赛的地方执行此代码。我想这样做,所以每次你运行程序时,它都会随机化团队的顺序,我试图做到这一点,这样就不会创建重复项。我有四个变量要使用。当我运行它时,似乎什么都没有发生,它没有崩溃,它只是表明它正在工作,但没有显示任何内容。

public void generateMatches() {
    w = (int)(Math.random()*3);
    x = (int)(Math.random()*3);
    y = (int)(Math.random()*3);
    z = (int)(Math.random()*3);
    do {                   
        w = (int)(Math.random()*3);
        x = (int)(Math.random()*3);
        y = (int)(Math.random()*3);
        z = (int)(Math.random()*3);
    } while (x == y || y == z || x == z || x == w || y == w || z == w);
}

【问题讨论】:

  • 您在该代码中的何处显示任何内容?
  • JVM 会崩溃还是不会崩溃?
  • 您的问题描述(“它没有崩溃”)与您的标题(“它只是崩溃”)相矛盾。它是哪一个? @Kayaman 也是对的。您需要编辑您的问题以澄清它,解决歧义和矛盾。

标签: java loops


【解决方案1】:

do-while 循环永远不会结束,因为您的条件始终是true。它永远不可能是 false,因为 (Math.random() * 3) 的输出是 0、1 或 2。因此,您的方法永远不能产生 4 个不同的数字。


一种解决方案是创建一个包含可能数字的列表,将其打乱并获取各个条目以分配给您的变量:

List<Integer> list = Arrays.asList(1, 2, 3, 4);
Collections.shuffle(list);
w = list.get(0);
x = list.get(1);
y = list.get(2);
z = list.get(3);

【讨论】:

  • 我完全忘记了Collections#shuffle。很好的解决方案。
猜你喜欢
  • 1970-01-01
  • 2016-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多