【问题标题】:Generating a random number outside of the oncreate method在 oncreate 方法之外生成一个随机数
【发布时间】:2013-04-16 03:27:21
【问题描述】:

我正在尝试设置我的活动,以便我可以从我的 onCreate 方法之外的方法生成一组随机数。这是我的活动的设置方式...

public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  this.optionOne();
  this.optionTwo();
  this.optionThree();
}

public void optionOne() {
  // generate a random number here
  int random = Math.random();

  // generate more random numbers and do more stuff here
} 

问题是,我在 onCreate 方法之外生成的任何随机数都被认为是“静态的”,并且数字始终为 0。如果我在 onCreate 方法中生成数字,它当然可以正常工作。我该如何解决这个问题?

【问题讨论】:

  • Math.random() 返回 0.0 到 1.0,如果你称它为 'int',它会舍弃小数,将其保留为 0。
  • @wtsang02 - 实际上我在做 Math.random(max_value),我只是删除了多余的数字以简化示例。虽然,您的其他答案解决了我的问题!谢谢你:)

标签: android methods random static


【解决方案1】:
private static Random ranGenerator=new Random();

将其声明为类的成员。
然后随时致电ranGenerator.nextInt() 获取它。

【讨论】:

  • 谢谢!你让我头疼不已。
【解决方案2】:

要生成随机数使用,这将在特定范围之间创建随机数

public void optionOne() {
   var=(int)(Math.random() * (max - min) + min)    //math.random will return integer values 
  // use your var wisely
} 

【讨论】:

    【解决方案3】:

    使用

    Random rand = new Random(); 
    int random = rand.nextInt();
    

    int random = rand.nextInt(range);
    

    根据文档here

    Math.random() Returns a pseudo-random double n, where n >= 0.0 && n < 1.0.
    

    【讨论】:

      【解决方案4】:

      这将帮助您创建非重复随机数的数组列表

       ArrayList<Integer> indexArray = new ArrayList<Integer>();
          for (i = 0; i < 202; ++i) {
                      number.add(i);
                      // number.add(num);
                  }
                  Collections.shuffle(number);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-01-03
        • 1970-01-01
        • 1970-01-01
        • 2018-04-21
        • 2011-09-18
        • 2014-03-20
        • 2011-04-07
        相关资源
        最近更新 更多