2013-05-16 55 views
0

我有一個關於參數傳遞的問題。在這個示例方法中,兩個想要調用methodOne但只使用x和y值而不是Color顏色。當我嘗試這樣做時,我在Eclipse中得到一個錯誤,「類型'示例類名'中methodOne(double x,double y,Color color)方法不適用於參數(double,double))」

可以methodTwo不調用另一個方法如果它不完全使用methodOne的所有參數?參數傳遞和方法調用

private void methodOne (double x, double y, Color color){ 
    statements...; 
    } 

private void methodTwo (x, y){ 
    methodOne(x, y); 
    statements...; 
} 
+0

這是什麼?方法1(x,y);這是一個有效的方法嗎?請糾正它。 –

+0

@JDeveloper我意識到我的錯誤,並且我編輯了它。 –

回答

1

你需要使用所有的參數來調用方法1。 (參數和參數的類型順序也很重要)

如果你沒有,你可以使用方法1作爲

private void methodTwo (x, y){ 
    method 1(x, y, null); 
    statements...; 
} 
+0

謝謝我明白這個簡單的答案。 –

0

方法名稱必須是一個單詞。您還需要提供最後一個參數。

private void method1 (double x, double y, Color color){ 
    statements...; 
    } 

private void method2 (x, y){ 
    method1(x, y, someColorOrNull); 
    statements...; 
} 

從JLS,第3.8節「標識符」:

標識符是對Java字母和Java 數字無限長度的序列,其中第一個必須是一個Java字母。

Identifier: 
    IdentifierChars but not a Keyword or BooleanLiteral or NullLiteral 

IdentifierChars: 
    JavaLetter 
    IdentifierChars JavaLetterOrDigit 

JavaLetter: 
    any Unicode character that is a Java letter (see below) 

JavaLetterOrDigit: 
    any Unicode character that is a Java letter-or-digit (see below) 
+0

哎呀,你是對的我剛剛編輯我的問題。 –

0

能方法2不能調用其他方法1,如果它不使用第三個參數方法1的所有參數?

它可以,但你必須重寫方法1是這樣的:

private void method 1 (double x, double y, Color color){ 
     statements...; 
     } 

    private void method 1 (double x, double y){ 
     statements...; 
     } 

    private void method 2 (x, y){ 
     method 1(x, y); 
     statements...; 
    } 
1

在您的代碼如下: -

private void methodTwo (x, y){ 
     methodOne(x, y); //Now this will show error , because parameter not matching 
     statements...; 
    } 

如果你不希望傳遞第3個參數則會顯示錯誤。因此,您必須傳遞第三個參數,並且出於您的目的,您可以通過null,因爲您沒有在函數定義中使用第三個參數。

IST解決方案: - :當你調用methodOne法2的參數如下

private void methodOne(double x, double y, Color color){ 
    //statements... same job; 
    } 

private void methodOne(double x, double y){ 
    //statements...same job; 
    } 

現在 - :

private void methodTwo (x, y){ 
     methodOne(x, y,null); 
     //statements...; 
    } 

第二個解決方案,您可以重載這個methodOne 2參數如下圖所示 -

private void methodTwo (x, y){ 
    methodOne(x,y); // Now the overloaded method will call 
    //statements...; 
} 
+0

非常感謝。選擇一種方法比另一種做法有一定的優點或缺點嗎? –

+0

是@JessicaM。基本上當你選擇方法重載的時候,你的應用程序或目的必須是多重結果。可能所有重載方法的輸出結果都有所不同。但爲了你的目的,你應該使用第一選項。快樂的投票:) –