使用BufferedReader实现Java虚数的四则运算
时间: 2023-12-12 20:57:19 浏览: 15
以下是使用BufferedReader实现Java虚数的四则运算的示例代码:
```
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Complex {
private double real;
private double imaginary;
public Complex(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
public Complex() {
this(0, 0);
}
public double getReal() {
return real;
}
public double getImaginary() {
return imaginary;
}
public Complex add(Complex other) {
return new Complex(real + other.real, imaginary + other.imaginary);
}
public Complex subtract(Complex other) {
return new Complex(real - other.real, imaginary - other.imaginary);
}
public Complex multiply(Complex other) {
double newReal = real * other.real - imaginary * other.imaginary;
double newImaginary = real * other.imaginary + imaginary * other.real;
return new Complex(newReal, newImaginary);
}
public Complex divide(Complex other) {
double denominator = other.real * other.real + other.imaginary * other.imaginary;
double newReal = (real * other.real + imaginary * other.imaginary) / denominator;
double newImaginary = (imaginary * other.real - real * other.imaginary) / denominator;
return new Complex(newReal, newImaginary);
}
public String toString() {
if (imaginary == 0) {
return String.format("%.2f", real);
} else if (real == 0) {
return String.format("%.2fi", imaginary);
} else {
return String.format("%.2f %+.2fi", real, imaginary);
}
}
}
public class ComplexCalculator {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the first complex number (a + bi): ");
String[] parts = reader.readLine().split("\\s+");
double real1 = Double.parseDouble(parts[0]);
double imaginary1 = Double.parseDouble(parts[1].substring(0, parts[1].length() - 1));
Complex c1 = new Complex(real1, imaginary1);
System.out.print("Enter the second complex number (a + bi): ");
parts = reader.readLine().split("\\s+");
double real2 = Double.parseDouble(parts[0]);
double imaginary2 = Double.parseDouble(parts[1].substring(0, parts[1].length() - 1));
Complex c2 = new Complex(real2, imaginary2);
System.out.println("1. Add");
System.out.println("2. Subtract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
System.out.print("Select an operation: ");
int operation = Integer.parseInt(reader.readLine());
Complex result;
switch (operation) {
case 1:
result = c1.add(c2);
break;
case 2:
result = c1.subtract(c2);
break;
case 3:
result = c1.multiply(c2);
break;
case 4:
result = c1.divide(c2);
break;
default:
System.out.println("Invalid operation selected.");
return;
}
System.out.println("Result: " + result);
}
}
```
在该示例中,我们定义了一个Complex类来表示虚数,并实现了它的四则运算方法。然后,我们使用BufferedReader从控制台读取两个虚数和一个操作,然后根据操作调用相应的方法来计算结果。最后,我们输出结果。