如何修正while循环中的随机数?

时间:2020-11-03 23:00:07

标签: java

我需要做的是使一个数字生成器在生成10次时停止,并显示直到达到10次为止的尝试次数。我也只需要使用while循环。现在是我的代码:

public static int RandomOccurrence()
{               
  int randNumber = (int)(Math.random()*20 + 1);
  int count = 0;

  while(randNumber != 11){
    System.out.println("The number generated is " + randNumber);
    count = count + 1;
  }
  return count;
}

这是函数调用:

int number = RandomOccurrence();
    System.out.println("It took " +number +" tries before 10 was generated");   
        
    System.out.println();
    System.out.println();

但是当我运行代码时,它将无限打印“生成的数字为2”。

4 个答案:

答案 0 :(得分:5)

这是您代码的固定版本,主要涉及将获取随机数的行移动到# A tibble: 3 x 1 CODE <chr> 1 04444 2 55555 3 00333 循环中:

while

抽样结果:

public static int RandomOccurrence()
{
    int randNumber = 0;
    int count = 0;

    while(randNumber != 10){//I changed the 11 to 10 because you said you wanted to stop at 10
        randNumber = (int)(Math.random()*20 + 1);//added
        System.out.println("The number generated is " + randNumber);
        count = count + 1;
    }
    return count;
}

System.out.println(RandomOccurrence());

答案 1 :(得分:3)

我真的更愿意为用户指出家庭作业问题的答案,而不是为他们提供有效的代码。因为我们试图“教一个人钓鱼”。

原始代码的问题在于,它必须在while循环内生成另一个随机数。最简单的方法是复制并粘贴用于生成第一个函数的函数调用。

P.S。:现在,您很快就会看到“有多种方法可以做到这一点!”

答案 2 :(得分:1)

您应该在执行while循环时更新随机数: 因此randNumber =(int)(Math.random()* 20 +1);应该在循环内

public static int RandomOccurrence(){               
    int count = 0;
    int randNumber = 0;

    while(randNumber != 11){
        randNumber = (int)(Math.random()*20 + 1);
        System.out.println("The number generated is " + randNumber);
        count = count + 1;
    }
    return count;
}

public static void main(String...args){
    int number = RandomOccurrence();
    System.out.println("It took " +number +" tries before 10 was generated");   
        
    System.out.println();
    System.out.println();
}

希望我能帮忙

答案 3 :(得分:0)

这里是1班轮:

long count = IntStream.generate(() -> (int)(Math.random() * 20 + 1))
    .takeWhile(i -> i != 11).count();

请参见live demo