编写一个简单计算器程序使用switch
时间: 2024-10-11 13:07:11 浏览: 54
编写一个简单的计算器程序使用`switch`语句,通常会涉及到用户输入选择操作类型(如加、减、乘、除),然后根据不同的选项执行相应的计算。这里是一个基本的示例,假设我们仅支持两个整数之间的运算:
```java
import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入运算符 (+, -, *, /): ");
String operator = scanner.nextLine();
System.out.println("请输入第一个数字: ");
int num1 = scanner.nextInt();
System.out.println("请输入第二个数字: ");
int num2 = scanner.nextInt();
switch (operator) {
case "+":
int sum = add(num1, num2);
System.out.println("结果: " + sum);
break;
case "-":
int difference = subtract(num1, num2);
System.out.println("结果: " + difference);
break;
case "*":
int product = multiply(num1, num2);
System.out.println("结果: " + product);
break;
case "/":
if (num2 != 0) { // 防止除以零错误
int quotient = divide(num1, num2);
System.out.println("结果: " + quotient);
} else {
System.out.println("错误: 除数不能为零");
}
break;
default:
System.out.println("无效的运算符,请重新输入.");
break;
}
scanner.close();
}
// 这些方法用于实际的数值运算
private static int add(int a, int b) {
return a + b;
}
private static int subtract(int a, int b) {
return a - b;
}
private static int multiply(int a, int b) {
return a * b;
}
private static int divide(int a, int b) {
return a / b;
}
}
阅读全文