学校作业,拿出来贴到博客里。。
输入的时候必须遵循诸如“5i+3”、“-i-4.8”、“i”等格式才能识别,输入两个虚数后会打印相加和相减的结果。
import java.util.Scanner;
public class Main
{
/**
* 检查输入的字符串是否合法。
* @param input 要被检查的字符串
* @return "ERROR",如果字符串非法;优化过的字符串,如果合法
*/
public static String check(String input)
{
if(input == null || input.equals("") || !input.contains("i"))
{
System.out.println("输入有误。按照0i+0计算。");
return "ERROR";
}
String s = input.trim();
if(s.startsWith("i"))
s = "1" + s;
else if(s.startsWith("-i"))
s = "-1" + s.substring(1);
if(s.endsWith("i"))
s += "+0";
int pos = s.indexOf("i");
try
{
Double.parseDouble(s.substring(0, pos));
//System.out.println(s + " 判断是否error时,虚部:" + s.substring(0, pos));
Double.parseDouble(s.substring(pos + 1));
//System.out.println(s + " 判断是否error时,实部:" + s.substring(pos + 1));
}
catch(Exception e)
{
System.out.println("输入有误。按照0i+0计算。");
return "ERROR";
}
return s;
}
public static void main(String[] arguments)
{
Scanner scan = new Scanner(System.in);
System.out.println("输入两个虚数,格式如:5i+8。");
String str1 = scan.next();
Complex c1 = new Complex(check(str1));
//System.out.println("check str1: " + check(str1));
String str2 = scan.next();
scan.close();
Complex c2 = new Complex(check(str2));
//String[] array = str1.split("i");
//System.out.println(Arrays.toString(array));
//System.out.println("check str2: " + check(str2));
System.out.println(c1.plus(c2));
System.out.println(c1.minus(c2));
}
}
/**
* 虚数类
* @author Hippo
*
*/
class Complex
{
private double realPart;
private double imagPart;
public Complex(String regex)
{
if(!regex.equals("ERROR"))
{
String[] array = regex.split("i");
this.imagPart = Double.parseDouble(array[0]);
this.realPart = Double.parseDouble(array[1]);
}
}
public String plus(Complex c)
{
//System.out.println("第一个数虚部:" + this.imagPart + "\n第一个数实部:" + this.realPart);
//System.out.println("第二个数虚部:" + c.imagPart + "\n第二个数实部:" + c.realPart);
double newImagPart = this.imagPart + c.imagPart;
double newRealPart = this.realPart + c.realPart;
if(newImagPart == 0 && newRealPart == 0)
return "0.0";
return optimize(newImagPart + "i" + (newRealPart > 0 && newImagPart != 0 ? "+" : "") + newRealPart);
}
public String minus(Complex c)
{
//System.out.println("第一个数虚部:" + this.imagPart + "\n第一个数实部:" + this.realPart);
//System.out.println("第二个数虚部:" + c.imagPart + "\n第二个数实部:" + c.realPart);
double newImagPart = this.imagPart - c.imagPart;
double newRealPart = this.realPart - c.realPart;
if(newImagPart == 0 && newRealPart == 0)
return "0.0";
return optimize(newImagPart + "i" + (newRealPart > 0 && newImagPart != 0 ? "+" : "") + newRealPart);
}
/**
* 优化结果。
* @param s 待优化的结果
* @return 优化后的结果
*/
public static String optimize(String s)
{
String optimized = s.trim();
String[] array = optimized.split("i");
if(Double.parseDouble(array[0]) == 0.0)
optimized = optimized.substring(optimized.indexOf("i") + 1);
if(Double.parseDouble(array[1]) == 0.0)
optimized = optimized.substring(0, optimized.indexOf("i") + 1);
return optimized;
}
}
最后结果如下。二进制表示小数会略有失真。
在进阶的路上,欢迎各位大侠指正。