java输入两个数,再输入任意运算符号,计算两个数结果,如果有小数保留两位,分别用if语句和switch语句书写
时间: 2024-09-27 07:16:31 浏览: 32
在Java中,我们可以使用`Scanner`类从用户那里获取输入,并通过if语句和switch语句来根据输入的运算符执行相应的计算。这里是一个简单的示例:
**使用if语句:**
```java
import java.util.Scanner;
public class CalculatorIf {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入第一个数字:");
double num1 = scanner.nextDouble();
System.out.println("请输入第二个数字:");
double num2 = scanner.nextDouble();
System.out.println("请输入运算符 (+, -, *, /):");
String operator = scanner.next();
double result;
if (operator.equals("+")) {
result = num1 + num2;
} else if (operator.equals("-")) {
result = num1 - num2;
} else if (operator.equals("*")) {
result = num1 * num2;
} else if (operator.equals("/")) {
// 如果除数为0,抛出异常
if (num2 == 0) {
throw new IllegalArgumentException("除数不能为零");
}
result = num1 / num2;
} else {
throw new IllegalArgumentException("无效的运算符");
}
// 使用DecimalFormat保留两位小数
DecimalFormat df = new DecimalFormat("#.00");
System.out.printf("结果:%.2f\n", df.format(result));
}
}
```
**使用switch语句:**
```java
import java.util.Scanner;
import java.text.DecimalFormat;
public class CalculatorSwitch {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入第一个数字:");
double num1 = scanner.nextDouble();
System.out.println("请输入第二个数字:");
double num2 = scanner.nextDouble();
System.out.println("请输入运算符 (+, -, *, /):");
String operator = scanner.next().toLowerCase();
switch (operator) {
case "+":
double result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
if (num2 != 0) {
result = num1 / num2;
} else {
throw new IllegalArgumentException("除数不能为零");
}
break;
default:
throw new IllegalArgumentException("无效的运算符");
}
DecimalFormat df = new DecimalFormat("#.00");
System.out.printf("结果:%.2f\n", df.format(result));
}
}
```
阅读全文