我正在尝试创建一个程序,提示用户输入包的重量并显示成本。我是switch语句的新手,这就是为什么我觉得它可能与这些语句有关。但是,我返回错误“无法从布尔值转换为int”。我已经看过其他情况,但没有找到解决方案。使用==没有改变它。
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");
}
}
}
答案 0 :(得分:2)
这篇文章是相关的 Switch statement for greater-than/less-than
使用开关时,只能在cases
switch(x)
{
case 1:
//...
break;
case 2:
//...
break;
}
答案 1 :(得分:1)
以下是无效的Java:
case weight <= 1:
您需要将switch
重新定义为一系列if
语句。
if (weight <= 1) {
System.out.println("The cost is 3.5");
} else if (weight <= 3) {
System.out.println("The cost is 5.5");
} ...