Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with Java Scanner sc.nextLine();

sry about my english :)
Im new to Java programming and i have a problem with Scanner. I need to read an Int, show some stuff and then read a string so i use sc.nextInt(); show my stuff showMenu(); and then try to read a string palabra=sc.nextLine();

Some one told me i need to use a sc.nextLine(); after sc.nextInt(); but i dont understand why do you have to do 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;
    }


}

Ty so much for your time and Help :D

like image 518
Jonathan B Avatar asked Mar 14 '10 23:03

Jonathan B


2 Answers

nextInt() only reads in until it's found the int and then stops.

You have to do nextLine() because the input stream still has a newline character and possibly other non-int data on the line. Calling nextLine() reads in whatever data is left, including the enter the user pressed between entering an int and entering a String.

like image 157
Ben S Avatar answered Oct 06 '22 23:10

Ben S


When you input a value (whether String, int, double, etc...) and hit 'enter,' a new-line character (aka '\n') will be appended to the end of your input. So, if you're entering an int, sc.nextInt() will only read the integer entered and leave the '\n' behind in the buffer. So, the way to fix this is to add a sc.nextLine() that will read the leftover and throw it away. This is why you need to have that one line of code in your program.

like image 31
Fadi Hanna AL-Kass Avatar answered Oct 06 '22 23:10

Fadi Hanna AL-Kass