用Java写个简易计算器
时间: 2023-08-29 19:08:18 浏览: 65
基于Java实现的(GUI)简易计算器【100012745】
5星 · 资源好评率100%
好的,以下是一个简单的 Java 计算器示例代码:
```java
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
double num2 = scanner.nextDouble();
System.out.print("Enter operator (+, -, *, /): ");
char operator = scanner.next().charAt(0);
double result;
switch(operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
default:
System.out.println("Invalid operator");
return;
}
System.out.println(num1 + " " + operator + " " + num2 + " = " + result);
}
}
```
这个程序将提示用户输入两个数字和一个操作符(加、减、乘、除),然后计算并输出结果。
阅读全文