gpt4 book ai didi

java - 如何调用和测试同名方法?

转载 作者:行者123 更新时间:2023-12-01 09:16:30 24 4
gpt4 key购买 nike

我收到了一项旨在测试计算器有效性的作业。他们给了我们一个默认的类,如下所示:

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);
}

}

您应该扩展这个旨在成为测试工具的类。执行此操作的说明如下:

  1. 创建一个名为 testParser() 的方法。
  2. 测试 x("12 + 5") 返回值为 17 的 Double。
  3. 测试 x("12 x 5") 返回值为 60 的 Double。
  4. 测试 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() 方法的帮助都会非常有帮助。谢谢。

最佳答案

您正在处理的是方法重载。您有 3 个同名的方法,但它们具有不同的方法签名。要调用特定方法,只需传入适当的参数即可。在这种情况下,您将执行以下操作:

 Calculator c = new Calculator();
String string = "b";
Double doubleObject = 1;
double doublePrimitive = 2;

c.x(string);
c.x(doubleObject);
c.x(doublePrimitive);

Java会根据传入的参数调用正确的方法。

关于java - 如何调用和测试同名方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40513939/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com