Problem with Java Scanner sc.nextLine ();

sry about my English :)
I am new to Java programming and I have a problem with the Scanner. I need to read Int, show some things, and then read the line, so I use sc.nextInt (); show my stuff showMenu (); , and then try to read the line palabra = sc.nextLine ();

Someone told me that I need to use sc.nextLine (); after sc.nextInt (); but I don’t understand why you need it :(

Here is my code:

public static void main(String[] args) {
    // TODO code application logic here
    Scanner sc = new Scanner(System.in);
    int respuesta = 1;

    showMenu();
    respuesta = sc.nextInt();
    sc.nextLine(); //Why is this line necessary for second scan to work?

    switch (respuesta){
        case 1:
            System.out.println("=== Palindromo ===");
            String palabra = sc.nextLine();
            if (esPalindromo(palabra) == true)
                System.out.println("Es Palindromo");
            else
                System.out.println("No es Palindromo");
        break;
    }


}

You are so much for your time and help: D

+5
source share
2 answers

nextInt() reads only until it finds an int and stops.

nextLine(), , , , int . nextLine() , int .

+7

(String, int, double ..) "enter", (aka '\n') . , int, sc.nextInt() '\n' . , - sc.nextLine(), . .

0

All Articles