2015-05-19 23 views
0

傳遞隨機對象作爲參數時遇到問題。將隨機對象作爲參數傳遞時的問題

我做了一個新文件來測試它,我得到了同樣的錯誤。誰能告訴我這有什麼問題?

import java.util.*; 
public class Practice { 
    public static void main(String[] args) { 
    Random r = new Random(1234); 
    Spring (Random r); 
    } 

    void Spring (Random r) { 
    r.nextInt(20); 
    } 
} 

我得到的錯誤是:

/tmp/Practice.java:5: error: ')' expected 
    Spring (Random r); 
       ^
/tmp/Practice.java:5: error: illegal start of expression 
    Spring (Random r); 
        ^
2 errors 
+0

此代碼是在幾個地方打破。你有沒有試過閱讀你的編譯器錯誤? –

+2

你應該傳遞參數作爲'Spring(r);' – MaxZoom

+1

也請使用以小寫字母開頭的方法名(大寫保留爲類) – MaxZoom

回答

0

要調用春天(......),你必須首先創建類的實例。要做到這一點,你必須調用構造函數:

Practice myPractice = new Practice(); 

在此之後,你可以打電話給你的春季方法:

myPractice.Spring(r); //Random must be left out at this place - only when declaring the function interface 
1

你有幾個問題....

這是你應該什麼在做(看解釋的意見):

public static void main(String[] args) { 
     Random r = new Random(1234); 
     //don't need Random here 
     //also call static method 
     Practice.Spring (r); 
} 
    //since you are calling a static method, you need to declare it static 
    //also it's good practice to add the methods access modifier. 
    private static void Spring (Random r) { 
     r.nextInt(20); 
} 
+0

太好了。這非常有幫助。爲什麼我想讓Spring變得私密? – CodingWill

+0

您以前的方式會默認爲'private',這只是一個明確的聲明。但是,將所有內容都設爲私有是一種很好的做法,除非有理由將其公開(像另一個類需要訪問該方法)。但在這種情況下,私人會很好地工作。 – BlackHatSamurai