2014-12-07 286 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(); 
     } 
     } 
    } 

} 
相關問題