JAVA模拟计算器
时间: 2023-08-13 14:04:55 浏览: 135
好的,下面是一个简单的JAVA模拟计算器代码示例:
```
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double num1, num2, result;
char operator;
System.out.print("Enter first number: ");
num1 = input.nextDouble();
System.out.print("Enter operator (+, -, *, /): ");
operator = input.next().charAt(0);
System.out.print("Enter second number: ");
num2 = input.nextDouble();
switch (operator) {
case '+':
result = num1 + num2;
System.out.print(num1 + " + " + num2 + " = " + result);
break;
case '-':
result = num1 - num2;
System.out.print(num1 + " - " + num2 + " = " + result);
break;
case '*':
result = num1 * num2;
System.out.print(num1 + " * " + num2 + " = " + result);
break;
case '/':
if (num2 == 0) {
System.out.print("Divide by zero error");
} else {
result = num1 / num2;
System.out.print(num1 + " / " + num2 + " = " + result);
}
break;
default:
System.out.print("Invalid operator");
break;
}
input.close();
}
}
```
运行程序后,用户输入第一个数字、运算符和第二个数字,程序根据运算符进行相应的计算,并输出结果。
阅读全文