随机不起作用

use*_*534 1 java random

我们在课堂上写了这段代码并且它工作得很好,但是当我把它复制到家里的电脑上时,我在'nextInt'下面有一条红线和一条消息说:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    The method nextInt(int) is undefined for the type Random
Run Code Online (Sandbox Code Playgroud)
public static void main(String[] args)
{
    Random rnd = new Random();
    int x, sum=0;
    for (int i = 0; i < 20; i++)
    {
        sum=0;
        x=rnd.nextInt(29)+2;
        for (int j = x-2; j < 0; j=j-2)
        {
            sum+=j;
        }
        System.out.println(x+ ","+ sum);
    }
}
Run Code Online (Sandbox Code Playgroud)

有人可以帮忙吗?

Jer*_*vel 11

我愿意打赌你现在的班级被命名了Random.是吗?改变它或使用

java.util.Random rnd = new java.util.Random();
Run Code Online (Sandbox Code Playgroud)

否则它将尝试实例化您自己的Random类,这显然没有该方法.

  • 实际上是java.util.Random (2认同)