Unreachable Code - Placing a break after a return in switch statement

I've tried looking this up, and although other people have asked this, their situation applies to different things (as far as I can tell).

I am learning Java, and I am creating a program that "talks" with the user, asking questions and stuff. As a step to actually learning the concepts of object-oriented programming, I created a class that helps my main project NOT be filled with the handling of questions, instead I put the handling and returns for most questions in a class called ConversationHelper.

I created a method in my ConversationHelper for asking Yes/No questions. Here is its code:

public boolean askYNQuestion(String question) {
    Scanner input = new Scanner(System.in);

    boolean isInputCorrect = false;

    while(isInputCorrect == false) {
    displayQuestion(question + " (Y or N)");
    String readin = input.nextLine();

    switch (readin.toLowerCase()) {
        case "n":
            return false;
            break;
        case "y":
            return true;
            break;
        case "yes":
            return true;
            break;
        case "no":
            return false;
            break;
        case "false":
            return false;
            break;
        case "true":
            return true;
            break;
        default:
            break;
    }
}
    System.out.println("THIS IS NOT SUPPOSED TO HAPPEN! FALSE DEFAULT!");
    return false;
}

The problem with this is more of an annoyance than anything else. Every break in the switch statement comes up with "unreachable code" because there is a return statement before it. However, this is meant to happen.

Netbeans now tells me, at build, that the "compiler ran with errors." Not only is this just annoying, but it makes it hard to tell if the error is this known error, or if it is another error that needs my attention, wasting time when I'm trying to make my program work.

I'm looking for either a better way to do this that won't generate errors, or a way to force disable this error from coming up. I am running Netbeans, with Java 8. Any help would be greatly appreciated.

Thanks!

Upvotes: 4

Views: 9319

Answers (1)

takendarkk
takendarkk

Reputation: 3442

A return will act as a break. There is no need to use both. If you receive the message that you have unreachable code, then there is either no point in it being there, or something you did previously is out of order logically.

As a second point, just to improve your code, you can combine conditions in your switch statement. If you have multiple items which will return the same thing, you can list them one after the other and put a single return for them all.

 switch (readin.toLowerCase()) {
    case "n":
    case "no":
    case "false":
        return false;
    case "y":
    case "yes":
    case "true":
        return true;
    default:
        break;
}

Upvotes: 8

Related Questions