简体   繁体   中英

cannot convert from boolean to int

I am trying to create a program that prompts the user to enter in the weight of the package and display the cost. I am new to the switch statement, which is why I feel it may have something to do with those statements. However, I return the error "cannot convert from boolean to int". I have looked at other situations where this comes up, but have not found a solution. Using == did not change it.

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");
        }

    }

}

This post is relevant Switch statement for greater-than/less-than

When you use switch you can only put equations in cases

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

case 2:
//...
break;

}

The following is not valid Java:

case weight <= 1:

You need to rephrase the switch as a series of if statements.

if (weight <= 1) {
    System.out.println("The cost is 3.5");
} else if (weight <= 3) {
    System.out.println("The cost is 5.5");
} ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM