【问题标题】:Looping for a random number of times java循环随机次数java
【发布时间】:2016-04-28 19:55:59
【问题描述】:

我的问题是我需要生成一个随机数,我已经完成了那部分很好,但是我需要使用该随机数进行循环。

例如,如果随机数是 13,则循环一段代码 13 次。

我遇到了麻烦,没有设法让任何工作,也无法在网上找到任何可以帮助我的东西。

基本上我想知道这是否可能?

谢谢大家。

【问题讨论】:

标签: java loops random


【解决方案1】:

这是一个简单的for 循环:

for (int i = new Random().nextInt(); i > 0; i--) {
   // do stuff
}

【讨论】:

    【解决方案2】:

    这是非常基本的 Java。一旦你随机化,你就会得到一个数字。只需在while 循环或for 循环中使用它。

    int x = GetRandomNumber(); //You have stated you have already done this...
    for(int i = 0; i < x; i++){
     //Do stuff here
    }
    

    【讨论】:

      【解决方案3】:

      给你:

      Random random = new Random();
      int a = random.nextInt(); // As you said, you got this so far...
      while (a > 0) { // if you need your random number for something, just copy its value to new variable and place it here instead of a
          // some code
          a--;
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-09-08
        • 1970-01-01
        • 2018-03-18
        • 2020-09-15
        • 2013-10-11
        • 2019-08-29
        • 2012-03-04
        • 1970-01-01
        相关资源
        最近更新 更多