1

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

    }

}
skrrgwasme
  • 9,358
  • 11
  • 54
  • 84
sjelmo5
  • 13
  • 1
  • 3
  • the switch(weight) is switching on an int, but the case expression "weight<=1" is a Boolean. This boolean cannot be converted to an int. hence the odd message. – Darius X. Sep 25 '14 at 17:22

2 Answers2

2

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;

}
Community
  • 1
  • 1
dimitris93
  • 4,155
  • 11
  • 50
  • 86
1

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");
} ...
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • So when would case statements be used then? i thought that switch statements got rid of the need to do multiple if statements – sjelmo5 Sep 25 '14 at 17:29
  • @sjelmo5: It is useful when you are selecting *between fixed values*. In your case, you are dealing with *ranges*, which makes the `switch` statement unsuitable. – NPE Sep 25 '14 at 17:32