【问题标题】:cannot convert from boolean to int无法从 boolean 转换为 int
【发布时间】: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

标签: java int boolean


【解决方案1】:

这篇文章是相关的 Switch statement for greater-than/less-than

当你使用 switch 时,你只能在 cases 中输入方程式

switch(x)
{
case 1:
//...
break;

case 2:
//...
break;

}

【讨论】:

    【解决方案2】:

    以下不是有效的 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");
    } ...
    

    【讨论】:

    • 那么什么时候使用case语句呢?我认为 switch 语句摆脱了执行多个 if 语句的需要
    • @sjelmo5:当您选择在固定值之间时很有用。在您的情况下,您正在处理 ranges,这使得 switch 语句不合适。
    猜你喜欢
    • 1970-01-01
    • 2023-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多