Why is using sc.nextLine () not the correct way to transfer control to the next line of input?

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 user input, I get an error like this:

Exception on 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 happening because of the "sc.nextLine ()" in the while loop. But I can't figure out why. I learned from here that I have to use sc.nextLine () after using sc.next () for the control to wrap to the next line of input. Any ideas where I'm going wrong?

+3


source to share


2 answers


From the documentation:

public String next()

Finds and returns the next complete token from this scanner. The first token is preceded by an input that matches the delimiter pattern

And also from the Scanner Documentation:



The scanner splits its input into tokens using the delimiter pattern that defaults to whitespace

And whitespace includes \n

and \r

.

Thus, when used nextLine()

to solve a problem, it is newline

permissible in a case nextInt()

, but it is not in a use case next()

.

+2


source


I think this will work for you. Try it :) You don't need this linesc.nextLine();



public static void main(String[] args)
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter number");
        int n=sc.nextInt();
        Map<String,String> directory= new HashMap<>();
        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");
        }

    }

      

+3


source







All Articles