java 设计一个简易计算器,能够实现加、减、乘、除、取余等
时间: 2023-10-14 22:04:48 浏览: 214
Javaswing实现简易计算器
下面是一个简单的 Java 计算器实现,支持加、减、乘、除、取余等操作:
```java
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("请输入第一个数:");
double num1 = input.nextDouble();
System.out.println("请输入运算符(+、-、*、/、%之一):");
String operator = input.next();
System.out.println("请输入第二个数:");
double num2 = input.nextDouble();
switch (operator) {
case "+":
System.out.println(num1 + " + " + num2 + " = " + (num1 + num2));
break;
case "-":
System.out.println(num1 + " - " + num2 + " = " + (num1 - num2));
break;
case "*":
System.out.println(num1 + " * " + num2 + " = " + (num1 * num2));
break;
case "/":
if (num2 == 0) {
System.out.println("除数不能为0!");
} else {
System.out.println(num1 + " / " + num2 + " = " + (num1 / num2));
}
break;
case "%":
if (num2 == 0) {
System.out.println("除数不能为0!");
} else {
System.out.println(num1 + " % " + num2 + " = " + (num1 % num2));
}
break;
default:
System.out.println("输入的运算符不合法!");
}
}
}
```
通过运行该程序,可以输入两个数字和运算符,计算出结果并输出到控制台。需注意除数为0的情况。
阅读全文