user6638423
user6638423

Reputation:

Input ignores IF statement if default in switch

I am doing a project (based on a tutorial). I have a switch statement and for each case, there's a default in case the user input is invalid, and I write on the console "Sorry, I do not understand your request". However, if the user instead of writing whatever, writes "exit", the program should end without that "I don't understand request" sentence showing up.

This is stated in my IF statement in the beginning. What my current project does at the moment when I type "exit" is showing that line and then stopping. I don't understand how the program completely ignores that IF statement in the beginning.

public class MainGame {

public static GameSave gameSave = new GameSave();
public static String user = "";
public static Scanner scanner = new Scanner(System.in);
public static String question;
public static int relationshipPoints;

public static void main(String[] args) {
        Random random = new Random();
        question = gameSave.loadGame();
        // relationshipPoints = gameSave.loadPoints();
        RelationshipPoints points = new RelationshipPoints();

        System.out.println("\n\t*** TEXT_GAME: FIRSTDATE ***\n");
        System.out.println("-You can exit the game at any time by typing 'exit'.-\n\n");

        while (true) {

            if (user.equalsIgnoreCase("exit")) {
                System.exit(1);
                break;
            } else {
                switch (question) {
                [...]
                case "2":
                    switch (user = scanner.next()) {
                    case "1":
                        System.out.println("\n\nThe guy you met last night was nice. You want to "
                                + "get back into contact with him. Why don't you check your phone for a number?");
                        question = "2A";
                        gameSave.saveGame("2A");
                        break;
                    case "2":
                        System.out.println("\n\n");
                        question = "0";
                        break;
                    default:
                        System.out.println("\nI do not understand your request.\n");
                        question = "2";
                        break;
                    }
                    break;
                case "2A": [...]

Upvotes: 0

Views: 60

Answers (2)

jack jay
jack jay

Reputation: 2503

user = scanner.nextLine(); insert this line just after entering in while loop. your problem occurs as you are checking user equal to exit but user has nothing so control goes to else portion.

Upvotes: 0

zcarioca
zcarioca

Reputation: 139

Try replacing your while(true) {...} with while ((user = scanner.next() != null) { ... }

It looks like you are trying to access the "user" data without first setting it.

Upvotes: 1

Related Questions