java编写一个简单的计算器程序,可以进行两个整数的加、减、乘、除运算。(
时间: 2023-11-11 14:01:18 浏览: 369
编写一个简单的Java计算器程序,可以进行两个整数的加、减、乘、除运算。
首先,我们需要定义一个Calculator类,并在其中定义一个静态方法,用于进行运算。这个方法接收两个整数和一个运算符,并返回计算结果。
```java
public class Calculator {
public static int calculate(int a, int b, char operator) {
int result = 0;
switch(operator) {
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
if(b != 0) {
result = a / b;
} else {
throw new ArithmeticException("除数不能为0");
}
break;
default:
throw new IllegalArgumentException("不支持的运算符");
}
return result;
}
}
```
接下来,我们可以在main方法中调用这个计算器方法,来进行计算并输出结果。
```java
public static void main(String[] args) {
int a = 10;
int b = 5;
char operator = '+';
int result = Calculator.calculate(a, b, operator);
System.out.println(a + " " + operator + " " + b + " = " + result);
operator = '-';
result = Calculator.calculate(a, b, operator);
System.out.println(a + " " + operator + " " + b + " = " + result);
operator = '*';
result = Calculator.calculate(a, b, operator);
System.out.println(a + " " + operator + " " + b + " = " + result);
operator = '/';
result = Calculator.calculate(a, b, operator);
System.out.println(a + " " + operator + " " + b + " = " + result);
}
```
以上代码会输出如下结果:
```
10 + 5 = 15
10 - 5 = 5
10 * 5 = 50
10 / 5 = 2
```
这样,我们就完成了一个简单的Java计算器程序,可以进行两个整数的加、减、乘、除运算。
阅读全文