0

[[Image description ]]

    System.out.print("Enter the key: ");
    int n=sc.nextInt();

    if(n==1)
    {
        System.out.println("Enter the task:");
        String k=sc.nextLine();
        System.out.println(k);
    }

Enter the key: is printing, after giving n=1, it just print Enter the task: and the whole program is terminated. But when I give sc.next() it working but my input has more than one word, is there any problem in sc.nextLine().

Tharun
  • 1
  • 2

3 Answers3

0

Whenever write scanner.nextInt() in that case this method doesn't return new line character or don't accept any input from user. So if you want perfect output then you need to put scanner.next() before getting string value from user. After that you can use scanner.nextLine() and it will be work fine.

Satyajit Bhatt
  • 211
  • 1
  • 7
0

This is a common conceptual problem. Read the java docs of these three functions. Meanwhile you can try the following code. It'll work.

System.out.print("Enter the key: ");
int n=sc.nextInt();
sc.nextLine();

if(n==1)
{
    System.out.println("Enter the task:");
    String k=sc.nextLine();
    System.out.println(k);
}
Pradip
  • 123
  • 1
  • 6
0

That's because the Scanner.nextInt method does not read the newline character in your input created by hitting "Enter," and so the call to Scanner.nextLine returns after reading that newline.

You will encounter the similar behaviour when you use Scanner.nextLine after Scanner.next() or any Scanner.nextFoo method (except nextLine itself).

The answer and the workaround are here.

frascu
  • 747
  • 5
  • 9