2

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?

1
  • When you use Scanner.nextInt(), it does not consume the new line (or other delimiter) itself so the next token returned will typically be an empty string. Thus, you need to follow it with a Scanner.nextLine() Commented Jun 9, 2013 at 15:43

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.