2014-12-07 285 views
2

我试着去产生与此代码的随机数,但经常收到此错误nextInt是未定义类型的方法安全随机

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

    at SecureRandom.main(SecureRandom.java:18) 

这里就是我试图

public class SecureRandom { 

    public static void main(String[] args) { 
    SecureRandom randomNumbers = new SecureRandom(); 
    for (int count = 1; count <=20; count++) { 

     int face = 1+randomNumbers.nextInt(6); 
     System.out.printf(" %d" , face); 

     if (count %5 ==0) { 
     System.out.println(); 
     } 

    } 

    } 

} 
+0

'在SecureRandom.main'是您的线索。你有两个名字完全相同的类,你认为Java如何处理? – 2014-12-07 11:02:33

回答

8

的编译器根据您定义的类来解析SecureRandom。您应该更改班级名称以避免与java.security.SecureRandom发生冲突。

1

由于您已经调用了自己的类SecureRandom,因此在您想要使用java.security.SecureRandom时,编译器在主方法中使用该类。 您可以强制编译器在代码中使用的类的规范名称使用后者:

public class SecureRandom { 

    public static void main(String[] args) { 
     java.security.SecureRandom randomNumbers = new java.security.SecureRandom(); 
     for (int count = 1; count <=20; count++) { 
     int face = 1+randomNumbers.nextInt(6); 
     System.out.printf(" %d" , face); 
     if (count %5 ==0) { 
      System.out.println(); 
     } 
     } 
    } 

} 
相关问题