java制作一个计算器
时间: 2023-09-29 21:03:17 浏览: 118
java计算器的制作
好的,以下是一个简单的 Java 计算器示例代码:
```java
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double num1, num2, result;
char operator;
System.out.print("Enter first number: ");
num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
num2 = scanner.nextDouble();
System.out.print("Enter operator (+, -, *, /): ");
operator = scanner.next().charAt(0);
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);
}
}
```
运行程序后,根据提示输入两个数字和操作符,计算器将输出结果。注意,此示例代码未处理输入错误的情况,例如输入非数字或不支持的操作符。
阅读全文