用java编写简单计算器
时间: 2023-11-26 10:05:15 浏览: 55
用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("请输入第一个数字:");
num1 = scanner.nextDouble();
System.out.print("请输入运算符(+、-、*、/):");
operator = scanner.next().charAt(0);
System.out.print("请输入第二个数字:");
num2 = scanner.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("除数不能为零");
break;
}
result = num1 / num2;
System.out.println(num1 + " / " + num2 + " = " + result);
break;
default:
System.out.println("错误的运算符");
}
scanner.close();
}
}
```
你可以将以上代码保存为 Calculator.java 文件,然后在命令行中使用以下命令编译和运行程序:
```bash
javac Calculator.java
java Calculator
```
然后按照程序提示输入两个数字和运算符即可。
阅读全文