我收到了一份旨在測試計算器有效性的作業。他們給了我們一個默認的課程去看起來像這樣:如何調用和測試具有相同名稱的方法?
public class Calculator {
Double x;
/*
* Chops up input on ' ' then decides whether to add or multiply.
* If the string does not contain a valid format returns null.
*/
public Double x(String x){
return new Double(0);
}
/*
* Adds the parameter x to the instance variable x and returns the answer as a Double.
*/
public Double x(Double x){
System.out.println("== Adding ==");
return new Double(0);
}
/*
* Multiplies the parameter x by instance variable x and return the value as a Double.
*/
public Double x(double x){
System.out.println("== Multiplying ==");
return new Double(0);
}
}
你想擴大這個類,旨在成爲一個測試設備。以下說明如下:
- 創建一個名爲testParser()的方法。
- 測試,X( 「12 + 5」)返回一個雙用值17
- 測試,X( 「12×5」)返回一個雙用值60
- 測試,X(」 12 [3「)返回null,因爲[不是有效的運算符。
下面是我所做的電流變化:
public class TestCalculator {
Double x;
/*
* Chops up input on ' ' then decides whether to add or multiply.
* If the string does not contain a valid format returns null.
*/
public Double x(String x){
return new Double(0);
}
public void testParsing() {
}
/*
* Adds the parameter x to the instance variable x and returns the answer as a Double.
*/
public Double x(Double x){
System.out.println("== Adding ==");
x("12 + 5");
return new Double(0);
}
/*
* Multiplies the parameter x by instance variable x and return the value as a Double.
*/
public Double x(double x){
System.out.println("== Multiplying ==");
x("12 x 5");
return new Double(0);
}
}
什麼,我主要是困惑的是我是如何調用實際的方法,因爲他們沒有得到任何唯一的名稱叫並且您不能更改方法的名稱,因爲這會更改數據類型。此外,他們爲什麼使用字符串數據類型來添加和相乘數字?如何開始編寫testParsers()方法會有幫助。謝謝。
過去了那麼你可以有效地指定由寂寂重載使用哪種方法的參數正確的方法。如果你傳入的參數是'String',它將使用接受一個字符串的重載等。至於「爲什麼他們使用String數據類型來添加和乘數?」 - 當然,這是一個問題,你應該問誰分配問題,而不是我們。 –
看來你是在java和本網站上都開始了,你應該看看像你這樣的其他問題,這裏是一個可能會讓你感興趣的問題: http://stackoverflow.com/questions/21058166/is可能的多個方法與同名但不同的參數在一個 –