user2468561
user2468561

Reputation: 23

Switch Statement Java

currently im working on my first calendar program but I have one problem

public class Kalender {
public static void main(String[] args) {
    Scanner userInput = new Scanner(System.in);

    String[] termine = new String[24];
    for (int i = 0; i<24;i++){
        termine[i]= "";

    }
    boolean fertig = false;
    while(!fertig){
        System.out.println("1 = Neuer Eintrag");
        System.out.println("2 = Termine ausgeben");
        System.out.println("3 = Programm beenden");

        int auswahl = userInput.nextInt();
        System.out.println("Ihre Auswahl: "+ auswahl);

        switch (auswahl){
            case 1:

                System.out.println("Wie viel Uhr? ");
                int nummer = userInput.nextInt();

                if (nummer<0 | nummer > 23) {
                    System.out.println("Eingabefehler");
                    break;
                }
                System.out.println("Termin: ");             //!Here Is The Problem!
                String eingabe = userInput.nextLine();

                termine[nummer] = eingabe;
                break;

            case 2:
                for (int i = 0; i<24;i++){
                    System.out.println(i+ "Uhr: "+termine[i]);
                    break;
                }

            case 3:
                fertig=true;
                break;

            default:
                System.out.println("Eingabefehler");

        }
    }
}

}

Output:

1 = Neuer Eintrag
2 = Termine ausgeben
3 = Programm beenden
1
Ihre Auswahl: 1
Wie viel Uhr? 
3
Termin: 
1 = Neuer Eintrag
2 = Termine ausgeben
3 = Programm beenden

Why does this code not offer the possibility to enter text after the System.out.println("Termin: "); statement?

Upvotes: 2

Views: 251

Answers (1)

Maroun
Maroun

Reputation: 95948

You should add another userInput.nextLine(); after int nummer = userInput.nextInt();.

That's because userInput.nextInt(); reads only the int value (and skips the \n which is the enter key you press right after).

So adding another userInput.nextInt(); will "swallow" the \n and the next one will read the actual String and we all will be happy.

Upvotes: 3

Related Questions