如何在循环时修复我的随机数?

Tyl*_*r P 3 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;
}
Run Code Online (Sandbox Code Playgroud)

这是函数调用:

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

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

Ste*_*eve 5

这是您的代码的固定版本,主要涉及将获取随机数的行移动到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());
Run Code Online (Sandbox Code Playgroud)

示例结果:

The number generated is 1
The number generated is 4
The number generated is 20
The number generated is 19
The number generated is 10
5
Run Code Online (Sandbox Code Playgroud)