javaa.add(b)方法
我正在做一个家庭作业项目。测试代码已经给出,我基本上必须让它工作 我一直在创建一个javaa.add(b)方法,java,addition,Java,Addition,我正在做一个家庭作业项目。测试代码已经给出,我基本上必须让它工作 我一直在创建一个add方法,我不知道如何使用测试页面上的输入。任何帮助都将不胜感激。以下是测试代码: import java.util.Scanner; // Test the Complex number class public class ComplexTest { public static void main(String[] args) { // use Scanner object to tak
add
方法,我不知道如何使用测试页面上的输入。任何帮助都将不胜感激。以下是测试代码:
import java.util.Scanner;
// Test the Complex number class
public class ComplexTest {
public static void main(String[] args) {
// use Scanner object to take input from users
Scanner input = new Scanner(System.in);
System.out.println("Enter the real part of the first number:");
double real = input.nextDouble();
System.out.println("Enter the imaginary part of the first number:");
double imaginary = input.nextDouble();
Complex a = new Complex(real, imaginary);
System.out.println("Enter the real part of the second number:");
real = input.nextDouble();
System.out.println("Enter the imaginary part of the second number:");
imaginary = input.nextDouble();
Complex b = new Complex(real, imaginary);
System.out.printf("a = %s%n", a.toString());
System.out.printf("b = %s%n", b.toString());
System.out.printf("a + b = %s%n", a.add(b).toString());
System.out.printf("a - b = %s%n", a.subtract(b).toString());
}
}
以下是我目前掌握的情况:
public class Complex {
private double real;
private double imaginary;
public Complex() {
this(0,0);
}
public Complex(double real) {
this(real,0);
}
public Complex(double real, double imaginary) {
this.real=real;
this.imaginary = imaginary;
}
public void setReal(double real) {
this.real = real;
}
public void setImaginary(double imaginary) {
this.imaginary = imaginary;
}
public double add(double a, double b) {
return a + b;
}
}
如果我理解正确,您可能希望您的
add
方法获取并返回一个复杂的
对象。试试这个:
public Complex add(Complex other) {
return new Complex(this.real + other.real, this.imaginary + other.imaginary);
}
这将创建一个新的复杂的实例。要在位修改,请使用以下命令:
public Complex add(Complex other) {
this.real += other.real;
this.imaginary += other.imaginary;
return this;
}
add方法的签名不应该更像public Complex add(Complex other)吗?您还需要重写toString(),并确定add(Complex other)是只是改变调用的复杂对象,还是返回一个表示self和other相加的新复杂对象。无论哪种方式,您都需要实数和虚数的getter来从Complex other参数获取这些值。@jshort您不需要getter方法“来从Complex other
参数获取这些值”。add
方法属于Complex
,因此它可以完全访问Complex
的所有字段,包括该之外的实例字段。在add
方法中写入this.real+other.real
非常合适。注意:将对象传递给printf
以与%s
格式说明符一起使用时,无需调用toString()
。如果对象不是字符串
,printf
将对其本身调用toString()
。@RichardTran您可以在定义them@RichardTran您可以从同一个类中访问私有字段。通过编辑,我认为“void”签名可能更清晰?让“构建器”对象以外的其他对象变异并返回自身是很奇怪的吗?shrug@muzzlator这绝对是不标准的,但我已经看过了。有一些插件可以将所有的void
方法转换为返回this
。这不是我该怎么做,但它符合OP问题中的用法。啊,以前从未见过。谢谢