java,从键盘上输入复数并进行判断输入的合法性,并进行加减法,结果打印输出
时间: 2024-05-02 16:16:58 浏览: 66
以下是一个简单的Java代码实现,可以实现输入复数、判断输入合法性、复数的加减法运算以及打印输出结果:
```java
import java.util.Scanner;
public class ComplexNumber {
private double real;
private double imaginary;
public ComplexNumber(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
public double getReal() {
return real;
}
public double getImaginary() {
return imaginary;
}
public ComplexNumber add(ComplexNumber other) {
double real = this.real + other.real;
double imaginary = this.imaginary + other.imaginary;
return new ComplexNumber(real, imaginary);
}
public ComplexNumber subtract(ComplexNumber other) {
double real = this.real - other.real;
double imaginary = this.imaginary - other.imaginary;
return new ComplexNumber(real, imaginary);
}
public String toString() {
if (imaginary >= 0) {
return real + " + " + imaginary + "i";
} else {
return real + " - " + (-imaginary) + "i";
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入第一个复数的实部和虚部(用空格隔开):");
double real1 = scanner.nextDouble();
double imaginary1 = scanner.nextDouble();
ComplexNumber c1 = new ComplexNumber(real1, imaginary1);
System.out.print("请输入第二个复数的实部和虚部(用空格隔开):");
double real2 = scanner.nextDouble();
double imaginary2 = scanner.nextDouble();
ComplexNumber c2 = new ComplexNumber(real2, imaginary2);
System.out.println("您输入的两个复数分别为:" + c1.toString() + "," + c2.toString());
// 判断输入合法性
if (Double.isNaN(real1) || Double.isNaN(imaginary1) || Double.isNaN(real2) || Double.isNaN(imaginary2)) {
System.out.println("您输入的复数不合法!");
return;
}
// 复数加减法运算
ComplexNumber sum = c1.add(c2);
ComplexNumber difference = c1.subtract(c2);
// 打印输出结果
System.out.println("两个复数的和为:" + sum.toString());
System.out.println("两个复数的差为:" + difference.toString());
}
}
```
在main方法中,首先通过Scanner类从键盘上读取两个复数的实部和虚部,并用ComplexNumber类的构造函数创建对应的ComplexNumber对象。接着判断输入的实部和虚部是否为NaN,如果是,则说明输入的复数不合法,直接输出错误信息并退出程序;否则,进行复数的加减法运算,并通过toString方法将结果转化为字符串输出到屏幕上。
阅读全文