我正在做一个家庭作业项目。给出了测试代码,我基本上必须使其工作。
我一直坚持创建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;
}
}
答案 0 :(得分:4)
如果我的理解正确,您可能希望您的add
方法同时采用和返回Complex
对象。试试这个:
public Complex add(Complex other) {
return new Complex(this.real + other.real, this.imaginary + other.imaginary);
}
这将创建一个新的Complex
实例。要就地修改,请使用以下命令:
public Complex add(Complex other) {
this.real += other.real;
this.imaginary += other.imaginary;
return this;
}