【发布时间】:2014-09-25 17:08:58
【问题描述】:
我正在尝试创建一个程序,提示用户输入包裹的重量并显示成本。我是 switch 语句的新手,这就是为什么我觉得它可能与这些语句有关。但是,我返回错误“无法从布尔值转换为整数”。我查看了其他出现这种情况的情况,但没有找到解决方案。使用 == 并没有改变它。
import java.util.Scanner;
public class Exercise03_18 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the weight of the package: ");
int weight = input.nextInt();
switch (weight) {
case weight <= 1:
System.out.println("The cost is 3.5");
break;
case weight <= 3:
System.out.println("The cost is 5.5");
break;
case weight <= 10:
System.out.println("The cost is 8.5");
break;
case weight <= 20:
System.out.println("The cost is 10.5");
default: System.out.println("The package cannot be shipped");
}
}
}
【问题讨论】:
-
switch(weight) 正在打开一个 int,但 case 表达式 "weight