0

When I run the above code, it skips the first input string and without taking the input string, it prints hs.size() and jumps to n=2.But from n=2, the code runs absolutely fine.It takes the input string and adds in the hash set.

Why it skips the input string for n=1?? Please help.

public class ch 
{
    public static void main(String[] args) 
    {
        HashSet hs=new HashSet();
        String s;
        Scanner console=new Scanner(System.in);
        int n=console.nextInt();

        for(int i=0;i<n;i++)
        {   
            s=console.nextLine();
            hs.add(s);
            System.out.println(hs.size());
        }
    }
}
shmosel
  • 42,915
  • 5
  • 56
  • 120

1 Answers1

0

It is because nextLine() directly after nextXXX() (XXX being any of Int, Float Double,etc) creates problem. nextXXX do not parse \n and nextLine() in such a case reads only \n left behind by nextXXX(). To resolve the issue, you can use an extra nextLine() just below nextInt() and your code will work just fine..

Vatsal Prakash
  • 549
  • 6
  • 16