I am new to Data Structure and I am trying to create an arraylist that accepts String values. I successfully created an empty arraylist but whenever I try to run it through a for loop, it returns empty value for the first item. I want to fill up array list with user values from the very first but I could not do it. I checked other related questions, saw Youtube tutorial but unable to figure out what problem my coding holds? Here is the snippet of code I tried:
public class fire {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter no. of members:: ");
int size = sc.nextInt();
ArrayList<String> nameList = new ArrayList<String>(size);
for (int i = 0; i < size; i++) {
System.out.println("Enter names:: ");
nameList.add(sc.nextLine());
}
System.out.println(nameList);
}
}
My output whenever I declare the size prints out empty value for the very first item but I want it to be user-given value. outPut
Enter no. of members::
4
Enter names::
Enter names::
John
Enter names::
Cena
Enter names::
Harry
[, John, Cena, Harry]
Process finished with exit code 0