java利用方法重载编写一个应用程序,用户可输入任意类型的2个数,输出2数之和(类型包含整数、浮点数、复数)
时间: 2024-10-11 08:04:05 浏览: 83
2020 兴业数金Java笔试题.docx
在Java中,我们可以利用方法重载(Overloading)来创建一个接受不同类型参数的加法运算函数,以便处理整数、浮点数以及复数的加法操作。下面是一个简单的示例:
```java
public class Calculator {
// 方法重载 - 整数相加
public int add(int a, int b) {
return a + b;
}
// 方法重载 - 浮点数相加
public float add(float a, float b) {
return a + b;
}
// 方法重载 - 复数相加(这里假设我们有一个自定义的ComplexNumber类)
// 注意:在Java中,标准库并不支持复数,需要自定义一个复杂数类
public ComplexNumber add(ComplexNumber c1, ComplexNumber c2) {
double real = c1.getReal() + c2.getReal();
double imag = c1.getImaginary() + c2.getImaginary();
return new ComplexNumber(real, imag);
}
}
class ComplexNumber {
private double real;
private double imaginary;
// getters and setters
public ComplexNumber(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
}
public class Main {
public static void main(String[] args) {
Calculator calculator = new Calculator();
System.out.println("Enter two integers to add: ");
Scanner scanner = new Scanner(System.in);
int integer1 = scanner.nextInt();
int integer2 = scanner.nextInt();
int sumInt = calculator.add(integer1, integer2); // 输出整数和
System.out.println("Enter two floats to add: ");
float float1 = scanner.nextFloat();
float float2 = scanner.nextFloat();
float sumFloat = calculator.add(float1, float2); // 输出浮点数和
System.out.println("Enter two complex numbers to add: ");
ComplexNumber complex1 = new ComplexNumber(scanner.nextDouble(), scanner.nextDouble());
ComplexNumber complex2 = new ComplexNumber(scanner.nextDouble(), scanner.nextDouble());
ComplexNumber sumComplex = calculator.add(complex1, complex2); // 输出复数和
}
}
```
在这个程序中,用户可以根据提示输入整数、浮点数或复数,然后通过调用相应的方法计算它们的和。
阅读全文