Search code examples
javaiteratorjava.util.scanner

nextLine() not working after next() method


package new_package;

import java.util.Scanner;

public class Test {

public static void main ( String args[])

{
Scanner input = new Scanner(System.in);

System.out.println("Enter a character");

char c = input.next().charAt(0);

System.out.println ( "Enter a string");

String s = input.nextLine();

System.out.println (c);
System.out.println (s); 

}

}

The output of this program after first execution is :

Enter a character

And after i enter the character c in the output looks like:

Enter a character

c

Enter a string

c

The problem with this program is i am not allowed to input the string which is supposed to be input with the help of the next line commend .

The program automatically takes the value "" for the string and prints the vacant string.

Why?


Solution

  • Add a nextLine() after next(), to consume the end of the line that contained the token you got by calling next(). Otherwise, the end of the line is consumed when you call String s = input.nextLine();, which leaves s empty.

    char c = input.next().charAt(0);
    input.nextLine(); // add this
    System.out.println ( "Enter a string");
    
    String s = input.nextLine();