java 定义一个复数类

2025-01-18 18:05:11
推荐回答(1个)
回答1:

//余下的自己完成

import java.util.Scanner;

public class ComplexOperation {

static Scanner s = new Scanner(System.in);

public Complex option(Complex c1, Complex c2, String opch) {
Complex r = new Complex();
if("+".equals(opch)) {
r.setReaPart(c1.getReaPart() + c2.getReaPart());
r.setVirPart(c1.getVirPart() + c2.getVirPart());

} else if("-".equals(opch)) {
r.setReaPart(c1.getReaPart() - c2.getReaPart());
r.setVirPart(c1.getVirPart() - c2.getVirPart());
}
return r;
}

public Complex read(String info) {
System.out.println(info);
Complex c = new Complex();
System.out.print("实部: ");
c.setReaPart(s.nextInt());
System.out.print("虚部: ");
c.setVirPart(s.nextInt());
return c;
}

public static void main(String[] args) {

// ComplexOperation co = new ComplexOperation();
// Complex c1 = co.read("输入复数一");
// Complex c2 = co.read("输入复数二");
// System.out.print("输入运算符: ");
// String opch = s.next();
// System.out.print("结果是: " + co.option(c1, c2, opch));
// double d = 2.36;
// int len = 1;
// String format = "%" + len + ".2f";
// System.out.printf(format, d);

}

}
class Complex{
private int reaPart;
private int virPart;

public Complex() {
}
public Complex(int r, int v) {
this.reaPart = r;
this.virPart = v;

}

public String toString() {
int tag = this.getVirPart();
if(tag == 0) {
return getReaPart() + "";
} else if(tag > 0) {
return getReaPart() + "+" + getVirPart() + "i";
} else {
return getReaPart() + "-" + -getVirPart() + "i";
}

}
public int getReaPart() {
return reaPart;
}
public void setReaPart(int reaPart) {
this.reaPart = reaPart;
}
public int getVirPart() {
return virPart;
}
public void setVirPart(int virPart) {
this.virPart = virPart;
}

}