【问题标题】:Can someone explain me why this "random number" is allways the same (1)? [duplicate]有人能解释一下为什么这个“随机数”总是相同的(1)吗? [复制]
【发布时间】:2021-08-26 07:09:53
【问题描述】:

我有一个类用于显示我的 GUI,称为 GUI,我还有另一个类称为 Dice,它应该为我做一些事情。

首先我只想添加方法 createDice() 应该创建一个随机数,我想在控制台中显示它。它在控制台中显示 allways 1。请帮我。我是新来的,现在我很想成为社区的一员:)

我的代码:

    //returns new dice (number between 1 and 6)
    public int createDice () {
        int dice = (int) Math.random()*6+1;
        return dice;
    }

【问题讨论】:

  • @Ivar 在您的链接中看到“xkcd”的那一刻,我知道这是那个漫画:-)
  • 最好使用专为此目的设计的Random.nextInt(int bound)return ThreadLocalRandom.current().nextInt(6) + 1;

标签: java random


【解决方案1】:

Math.random 返回一个介于 0 和 1 之间的随机数。当您将其转换为 int 时,您将得到 0、0*ANYNumber = 0,并且 0 加 1 为 1。

解决方案:使用括号

(int) ((Math.random()*6) + 1);

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-22
  • 1970-01-01
  • 2019-10-24
  • 2018-10-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多