定义两个类,一个定义4个方法,分别求这两个数的和、差、乘、除结果并输出。另一个类具有x和y两个静态变量,在main()方法中,用户应能输入这两个数并调用前一个类的方法进行四则运算
时间: 2024-09-27 19:16:19 浏览: 24
java编写一个类,该类可以进行加、减、乘、除四则运算,并且输出运算结果
好的,我们可以定义两个Java类来满足这个需求。首先,我们创建一个基础操作类`BasicCalculator`,它有四个方法来进行加减乘除:
```java
public class BasicCalculator {
public int add(int num1, int num2) {
return num1 + num2;
}
public int subtract(int num1, int num2) {
return num1 - num2;
}
public int multiply(int num1, int num2) {
return num1 * num2;
}
public double divide(int num1, int num2) throws ArithmeticException {
if (num2 != 0) {
return (double) num1 / num2;
} else {
throw new ArithmeticException("Cannot divide by zero");
}
}
}
```
然后,我们创建一个名为`NumberInput`的类,用于接收用户的输入,并利用`BasicCalculator`类进行计算:
```java
import java.util.Scanner;
public class NumberInput {
static int x = 0;
static int y = 0;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the first number:");
x = scanner.nextInt();
System.out.println("Enter the second number:");
y = scanner.nextInt();
BasicCalculator calculator = new BasicCalculator();
int sum = calculator.add(x, y);
int difference = calculator.subtract(x, y);
int product = calculator.multiply(x, y);
try {
double quotient = calculator.divide(x, y);
System.out.println("Sum: " + sum);
System.out.println("Difference: " + difference);
System.out.println("Product: " + product);
System.out.println("Quotient: " + quotient);
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
}
scanner.close();
}
}
```
在这个例子中,用户可以在`main`方法中输入两个数字,然后`NumberInput`类会调用`BasicCalculator`的方法来完成加减乘除运算。
阅读全文