SuddenLife
SuddenLife

Reputation: 5

Switch statement prematurely closing

I'm currently working on a project for a university course, and I'm having issues with a switch statement ending prematurely. I can't seem to figure out what I'm doing wrong.

It's supposed to take the user's input, and if not one of the cases, restart the switch statement. However, as soon as one invalid char is put in, the switch statement closes completely and ends the program.

I currently have it set to print out each code if it enters correctly, however,

public static void companyClassificationCode() {
    char companyCode;

    System.out.print("Please enter your company classification code: ");
    companyCode = console.next().charAt(0);
    switch (companyCode) {
        case 'c':
        case 'C':
            System.out.println("C");
            companyCode = 'C';
            break;
        case 'l':
        case 'L':
            System.out.println("L");
            companyCode = 'L';
            break;
        case 'n':
        case 'N':
            System.out.println("N");
            companyCode = 'N';
            break;
        case 's':
        case 'S':
            System.out.println("S");
            companyCode = 'S';
            break;
        default:
            System.out.print("An invalid code has been entered. Please enter your company classification code: ");

    }
}

Upvotes: 0

Views: 140

Answers (1)

Tasos P.
Tasos P.

Reputation: 4114

You probably want to wrap the switch statement in a loop. The following code will loop until a valid code is entered; invalid values are reverted to the initial value (a single space character) and the loop is restarted.

    public static void companyClassificationCode() {
        char companyCode = ' ';

        while (companyCode == ' ') {
            System.out.print("Please enter your company classification code: ");
            companyCode = console.next().charAt(0);
            switch (companyCode) {
                case 'c':
                case 'C':
                    System.out.println("C");
                    companyCode = 'C';
                    break;
                case 'l':
                case 'L':
                    System.out.println("L");
                    companyCode = 'L';
                    break;
                case 'n':
                case 'N':
                    System.out.println("N");
                    companyCode = 'N';
                    break;
                case 's':
                case 'S':
                    System.out.println("S");
                    companyCode = 'S';
                    break;
                default:
                    System.out.print("An invalid code has been entered. Please enter your company classification code: ");
                    companyCode = ' ';
            }
        }
    }

Upvotes: 1

Related Questions