编写一个复数类,可以进行复数加法和减法运算。编写一个包含main方法的类(应用程序)测试该复数类。要求该复数类至少包含一个无参的构造方法和一个带参的构造方法;数据成员包括复数的实部和虚部,为double类型;包括两个方法,分别实现复数的加法和减法运算。示例输出如图所示。
package com.company;
import javax.swing.*;
class Complex{
/** 实部 */
private final double real;
/** 虚部 */
private final double image;
/** 默认构造函数 */
public Complex(){
this.real = 0;
this.image = 0;
}
/**
* 带参构造函数
* @param real 实部
* @param image 虚部
*/
public Complex(double real, double image){
this.real = real;
this.image = image;
}
/**
* 复数加法
* @param other 加数
* @return 和
*/
public Complex add(Complex other){
return new Complex(real + other.real, image + other.image);
}
/**
* 复数减法
* @param other 减数
* @return 差
*/
public Complex minus(Complex other){
return new Complex(real - other.real, image - other.image);
}
@Override
public String toString(){
if(real == 0 && image == 0) {
return "0";
}
String r = real == 0 ? "" : String.valueOf(real);
String i = image == 0 ? "" : image > 0 ? "+" + image + "*i" : image + "*i";
return r + i;
}
/**
* 显示复数a和复数b做加法和减法的结果
* @param other 加数和减数
*/
public void showAddAndMinus(Complex other){
JOptionPane.showMessageDialog(null, "a = " + this + "\n" +
"b = " + other + "\n" +
"a + b = " + add(other) + "\n" +
"a - b = " + minus(other) + "\n");
}
}
public class Main {
public static void main(String[] args) {
JTextField c1Real = new JTextField(5);
JTextField c1Image = new JTextField(5);
JTextField c2Real = new JTextField(5);
JTextField c2Image = new JTextField(5);
JPanel jPanel = new JPanel();
jPanel.add(new JLabel("第一个复数 实部: "));
jPanel.add(c1Real);
jPanel.add(new JLabel("虚部: "));
jPanel.add(c1Image);
jPanel.add(new JLabel("第二个复数 实部: "));
jPanel.add(c2Real);
jPanel.add(new JLabel("虚部: "));
jPanel.add(c2Image);
int result = JOptionPane.showConfirmDialog(null, jPanel,"复数运算", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION){
Complex c1 = new Complex(Double.parseDouble(c1Real.getText()), Double.parseDouble(c1Image.getText()));
Complex c2 = new Complex(Double.parseDouble(c2Real.getText()), Double.parseDouble(c2Image.getText()));
c1.showAddAndMinus(c2);
}
}
}