Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Switch Statement code block not executing

PriapusPriapus Member Posts: 39

Hi all,
I am using a switch statement to output a message depending on whether the user's input falls within a range of numbers (<= 49 and >= 75). However, only the code in the statement after the switch block is executed. Any reason why this is so? Below is a sample of my code where only the "End of program" message is output:

public class Temperature
{
public static void main(String[] args)
{
int temperature;
Scanner input = new Scanner(System.in);

    System.out.print("Enter a dew point temperature (F): ");
    temperature = input.nextInt();

    if (temperature <= 49 && temperature >= 75)
        switch(temperature)
        {
            case 1:  System.out.println("Extremely uncomfortable");
                    break;
            case 2: System.out.println("Very humid");
                    break;                                                
            case 3: System.out.println("Somewhat uncomfortable");
                    break;
            case 4: System.out.println("OK");
                    break;
            case 5: System.out.println("Comfortable");
                    break;
            case 6:  System.out.println("Very Comfortable");                            
                    break;
            case 7:    System.out.println("A bit dry");
                    break;
        }// end switch  
    System.out.println("End of program");
}// end main method

}// end class

Answers

  • B00B00 Member Posts: 98 ✭✭✭

    Temperature is 49-75 but your cases are for 1-7.

  • B00B00 Member Posts: 98 ✭✭✭

    Just noticed your if statement. A number cannot be lower than 50 and higher than 74 at the same time, thus nothing inside it is executed.

  • PriapusPriapus Member Posts: 39

    Does this mean that i have to use a case statement for each number between 49 and 75? Also i did change the comparison operator to an OR (||) but got the same result.

  • B00B00 Member Posts: 98 ✭✭✭

    Cases are for exact value. If you want to test for ranges then use if-else statements.

  • PriapusPriapus Member Posts: 39

    Actually the programming exercise was that we solve this problem using both a selection structure and a case structure. I have already solved it using the if-else- if selection structure.

  • B00B00 Member Posts: 98 ✭✭✭

    Then good luck using case on every number in the range.

  • SixtyHzSixtyHz USMember Posts: 13

    You if statement will always be false as noted above.
    Also the switch statement will never trigger because your values are too high... what you could do is scale the temperature down (by dividing it by a number that will get you in the range). Also good practice to use a default case to catch any errors...

Sign In or Register to comment.