Niv
Niv

Reputation: 133

got a unreachable statement on switch statment

import java.util.Scanner;
public class Program{
public static void main(String[] args){
    int day;
    int month = 5;
    int year = 2018;
    String str;
    Scanner s = new Scanner(System.in);
    day = s.nextInt();
    switch(day) {
        case 1:
            str = "Sunday";
        break;

        case 2:
            str = "Monday";
        break;

        case 3:
            str = "Tuesday";
        break;

        case 4:
            str = "Wednesday";
        break;

        case 5:
            str = "Thursday";
        break;

        case 6:
            str = "Friday";
        break;

        case 7:
            str = "Saturday";
        break;

     System.out.println(str);
    }
  }
}

Hello Why I Keep get a error:

unreachable statement System.out.println(str); OR I SOMETIMES GET variable str might not have been initialized System.out.println(str); Thanks for help

Upvotes: 1

Views: 2953

Answers (2)

Amit
Amit

Reputation: 1560

You got the error because your break statement exits the switch statement before reaching the sysout statement.

use the sysout outside of switch statement.

Upvotes: -1

T.J. Crowder
T.J. Crowder

Reputation: 1075427

unreachable statement System.out.println(str); OR I SOMETIMES GET variable str might not have been initialized

With what you have in your question, it's "unreachable statement" because the System.out.println(str) is within case 7 after break, so it can't be reached.

If you move it to where it should be, after the closing } of the switch, you'll get the "variable str might not have been initialized" because that's true if day isn't any of the values in the switch's cases, which it very well may not be as this is user input.

I'd put the System.out.println(str); after the switch and add a default to the switch:

default:
    throw new IllegalStateException("'day' cannot have the value " + day);

That will prevent both errors. (Or in your specific case, you may use a different exception, or just output a message and then return; to exit main since this is user input.)

Here's are those changes in situ, for clarity:

public static void main(String[] args){
    int day;
    int month = 5;
    int year = 2018;
    String str;
    Scanner s = new Scanner(System.in);
    day = s.nextInt();
    switch(day) {
        case 1:
            str = "Sunday";
        break;

        case 2:
            str = "Monday";
        break;

        case 3:
            str = "Tuesday";
        break;

        case 4:
            str = "Wednesday";
        break;

        case 5:
            str = "Thursday";
        break;

        case 6:
            str = "Friday";
        break;

        case 7:
            str = "Saturday";
        break;

        default:
            throw new IllegalStateException("'day' cannot be " + day);
    }
    System.out.println(str);
}

Upvotes: 6

Related Questions