Why using sc.nextLine() isn't the correct way to transfer control to next line of input ?

Viewed 931

I was solving HackerRank "30 Days Of Code" problem 8.

This is the code I wrote:

import java.util.*;
import java.io.*;
public class Directory
{
    public static void main(String args[])throws NoSuchElementException
    {
        Scanner sc=new Scanner(System.in);
        //System.out.println("Enter number");
        int n=sc.nextInt();
        sc.nextLine();
        Map<String,String> Directory= new HashMap<String,String>();
        for (int i=0;i<n;i++)
        {
         //System.out.println("Enter name and phone number");
         String name=sc.next();
         String ph=sc.next();
         sc.nextLine();
         Directory.put(name,ph);
        }
         while(sc.hasNext())
         {
         String s = sc.next();
         sc.nextLine();
         String phoneNumber = Directory.get(s);
         System.out.println((phoneNumber != null) ? s + "=" + phoneNumber : "Not found");
        }

    }
}

When I run this code with the custom input I get an error as follows:

Exception in thread "main" java.util.NoSuchElementException: No line found at java.util.Scanner.nextLine(Scanner.java:1585) at Directory.main(Directory.java:23)

I think this is occurring due to the "sc.nextLine()" in the while loop. But I'm not able to figure out why. I had learnt from here that I should use sc.nextLine() after using sc.next() so that the control is transferred to the next line of input. Any ideas where I am going wrong?

2 Answers
Related