使用Java编写一个简易计算器
时间: 2023-05-27 11:06:15 浏览: 141
以下是一个简单的Java计算器程序:
```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("请输入第一个数字:");
num1 = input.nextDouble();
System.out.print("请输入运算符号(+、-、*、/):");
operator = input.next().charAt(0);
System.out.print("请输入第二个数字:");
num2 = input.nextDouble();
switch (operator) {
case '+':
result = num1 + num2;
System.out.println(num1 + " + " + num2 + " = " + result);
break;
case '-':
result = num1 - num2;
System.out.println(num1 + " - " + num2 + " = " + result);
break;
case '*':
result = num1 * num2;
System.out.println(num1 + " * " + num2 + " = " + result);
break;
case '/':
if (num2 == 0) {
System.out.println("除数不能为零!");
} else {
result = num1 / num2;
System.out.println(num1 + " / " + num2 + " = " + result);
}
break;
default:
System.out.println("运算符输入有误!");
}
input.close();
}
}
```
使用该程序,用户可以输入两个数字和一个运算符,程序将根据运算符计算结果并输出。例如,输入“3 + 5”,程序将输出“3.0 + 5.0 = 8.0”。
阅读全文