我收到了一份旨在测试计算器有效性的作业。他们给了我们一个默认的课程去看起来像这样:如何调用和测试具有相同名称的方法?
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可能的多个方法与同名但不同的参数在一个 –