2013-12-10 84 views
1

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

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    The method nextInt(int) is undefined for the type Random 

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); 
    } 
} 

谁能帮助?

+15

不要告诉我你已经命名你的班级为随机' – Sage

+0

也许尝试播种随机数发生器? “new Random(System.currentTimeMillis());” –

+0

[Java的可能的重复 - 方法睡眠(int)未定义的类型线程](http://stackoverflow.com/questions/8591703/java-the-method-sleepint-is-undefined-for-the-type -thread) –

回答

11

我愿意赌你当前的课程名为Random。是吗?更改或使用

java.util.Random rnd = new java.util.Random(); 

否则,它会尝试实例自己Random类,这显然不具备这种方法。

+2

这实际上是java.util.Random – Chiron

+1

你错过了Chiron ...... –

+0

他是正确的。增加了''',否则它不起作用。 –