package Myjava;
//import java.lang.
//修复一小点输入不当导致崩溃
import java.util.Scanner;
public class Complex {
double real ,virt;
public static void main(String[] args) {
// TODO 自动生成的方法存根
var in = new Scanner(System.in);
Complex matf = new Complex();
Complex mats = new Complex();
System.out.print("请输入第一个复数:");
String input = in.nextLine();
matf.toComplex(input);
System.out.print("请输入第二个复数:");
input = in.nextLine();
mats.toComplex(input);
Complex temp = new Complex();
temp.copy(matf);
System.out.println("模分别为:" + matf.mod() + " " + mats.mod());
if(matf.compareMod(mats)) {
System.out.println("两数模相等");
}else {
System.out.println("两式模不等");
}
if(matf.compareSame(mats)) {
System.out.println("两数相等");
}else {
System.out.println("两式不等");
}
temp.copy(matf);
temp.add(mats);
System.out.println("两式之和:" + temp.toString());
temp.copy(matf);
temp.sub(mats);
System.out.println("(1):" + matf.toString() + "减 (2):" + mats.toString() + "值为:" + temp.toString());
temp.copy(mats);
temp.sub(matf);
System.out.println("(2):" + mats.toString() + "减 (1):" + matf.toString() + "值为:" + temp.toString());
}
public void copy(Complex value) {
this.real = value.real;
this.virt = value.virt;
}
public String toString() {
String flag = "+";
if (this.virt < 0) {
flag = "";
}
return (this.real + flag + this.virt + "i");
}
public void print() {
String flag = "+";
if (this.virt < 0) {
flag = "";
}
System.out.println(this.real + flag + this.virt + "i");
}
public void toComplex(String str) {
this.real = 0;
this.virt = 0;
str = str.replaceAll(" ","");
//System.out.println("old" + str);
str = str.toLowerCase();
//System.out.println("old" + str);
String temp = str;
int indexSub = temp.indexOf("-", 1);
int indexAdd = temp.indexOf("+", 1);
if(indexSub != -1 || indexAdd != -1) {
//有两个部分
if (indexSub > indexAdd) {
indexAdd = indexSub;
}
//分离虚实两部分
str = temp.substring(0,indexAdd);
temp = temp.substring(indexAdd,temp.length());
}else {
//只有一个部分
temp = "0";
}
String strs[] = {str,temp};
//System.out.println("STRS:" + temp + str);
for (String retval: strs) {
if((retval.length() == 2 && retval.charAt(1) == 'i') ) {
retval = retval.charAt(0) + "1i";
}
if ((retval.length() == 1 && retval.charAt(0) == 'i')) {
retval = "1i";
}
if (retval.charAt(retval.length() - 1) == 'i') {
this.virt = virt + Double.valueOf(retval.substring(0,retval.length() - 1));
}else {
this.real = real + Double.valueOf(retval);
}
}
//System.out.print("mat:" + real + "+" + virt + 'i');
}
public void add(Complex value) {
this.real += value.real;
this.virt += value.virt;
}
public void sub(Complex value) {
this.real -= value.real;
this.virt -= value.virt;
}
public boolean compareMod(Complex value) {
if (this.mod() != value.mod()) {
return false;
}
return true;
}
public boolean compareSame(Complex value) {
if (this.mod() != value.mod()) {
return false;
}else if(this.real != value.real){
return false;
}
return true;
}
public float mod() {
return (float) Math.sqrt(this.real * real + virt * virt);
}
}