0
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?

arpansen
  • 205
  • 1
  • 13
  • Possible duplicate of [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) – GBlodgett Mar 08 '19 at 04:30

1 Answers1

0

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();
Eran
  • 359,724
  • 45
  • 626
  • 694