用java语言编写一个简易计算器并在终端编译
时间: 2023-09-10 21:11:54 浏览: 109
好的,以下是一个简单的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 second number: ");
num2 = input.nextDouble();
System.out.print("Enter operator (+, -, *, /): ");
operator = input.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);
}
}
```
将上述代码保存为Calculator.java文件,打开命令行终端,进入文件所在目录,执行以下命令进行编译:
```
javac Calculator.java
```
编译成功后,在终端中输入以下命令运行程序:
```
java Calculator
```
程序会提示您输入两个数字和运算符,之后输出计算结果。
阅读全文