j ava简易计算器代码
时间: 2023-06-21 18:11:39 浏览: 161
java简易计算器代码
以下是一个简单的 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 the first number: ");
double num1 = input.nextDouble();
System.out.print("Enter the second number: ");
double num2 = input.nextDouble();
System.out.print("Enter an operator (+, -, *, /): ");
char operator = input.next().charAt(0);
double result;
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);
}
}
```
运行代码后,会要求用户输入两个数字和操作符。根据操作符执行相应的运算,最后输出结果。
阅读全文