用Java编写一个计算器
时间: 2023-08-20 13:07:14 浏览: 87
以下是使用Java编写简单的计算器的示例代码:
```java
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter first number: ");
double num1 = input.nextDouble();
System.out.print("Enter second number: ");
double num2 = input.nextDouble();
System.out.print("Enter operator (+, -, *, /): ");
char operator = input.next().charAt(0);
double result = 0.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);
}
}
```
该程序使用Scanner类接受用户输入的两个数字和运算符,并使用switch语句计算结果。最后,结果将被打印到控制台上。
阅读全文