class test {
public static void main(String[] args) {
String s = "(2,3i)+(4,5i)";
int p1 = s.indexOf("+");
String one = s.substring(0, p1);
String two = s.substring(p1 + 1);
Complex c1 = convert(one);
Complex c2 = convert(two);
Complex c = Complex.add(c1, c2);
System.out.println(c);
//把一个字符串类似(2,3i)转化为Complex对象
}
private static Complex convert(String input) {
int p2 = input.indexOf(",");
double x, y;
x = Double.parseDouble(input.substring(1, p2));
y = Double.parseDouble(input.substring(p2 + 1, input.length() - 2));
return new Complex(x, y);
}
}
class Complex {
double real;
double image;
public Complex(double real, double image) {
this.real = real;
this.image = image;
}
@Override
public String toString() {
return "Complex{" +
"real=" + real +
", image=" + image +
'}';
}
public static Complex add(Complex c1, Complex c2) {
return new Complex(c1.real + c2.real, c1.image + c2.image);
}
}
Java复数运算
最新推荐文章于 2024-08-16 23:08:28 发布