I am trying to add elements to hashset, but it gets an empty element into it.
Initially I tried,
import java.util.*;
public class SetTrial{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int number = sc.nextInt();
HashSet<String> names = new HashSet<String>();
for(int j=0; j<number;j++)
{
String text = sc.nextLine();
names.add(text);
}
System.out.println(names);
}
}
When I give input as,
5
a
b
c
d
e
It seems to only accept input till d
and execute print displaying
[, a, b, c, d]
My guess was that it is accepting a newline at beginning, so I added a sc.next()
in the code.
import java.util.*;
public class SetTrial{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int number = sc.nextInt();
HashSet<String> names = new HashSet<String>();
sc.next();
for(int j=0; j<number;j++)
{
String text = sc.nextLine();
names.add(text);
}
System.out.println(names);
}
}
Although this time it seems to accept all of the input properly, the result is
[, b, c, d, e]
So the problem must be something else. How do I fix this?