0

I am trying to get input in collections using for loop but somehow output displays 0th position empty

Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
ArrayList<String> b = new ArrayList<String>();

String abc;
for (int i = a; i > 0; i--) {
  abc = sc.nextLine();
  b.add(abc);
}

I expect output to be:

[a, d, b, c, e]

but actual output is:

[, a, d, b, c]
Zabuzard
  • 20,717
  • 7
  • 45
  • 67
  • As explained in the linked duplicate, you want `int a = Integer.parseInt(sc.nextLine());` instead of using `nextInt`. – Zabuzard May 16 '19 at 18:38
  • 1
    Note that your `for` loop is kind of unusual. Idiomatic is to create an increasing index, so `for (int i = 0; i < a; i++)`. – Zabuzard May 16 '19 at 18:39

1 Answers1

0

Add sc.nextLine() to skip the enter key:

Scanner sc = new Scanner(System.in);
int a;
String abc;
a = sc.nextInt();
sc.nextLine();
ArrayList<String> b = new ArrayList<String>();
for (int i = a; i > 0; i--) {
   abc = sc.nextLine();
   b.add(abc);
}
HelloWorld
  • 171
  • 1
  • 12