-1

I created an arrayList to store String values.When i am going to fetch values from my arrayList it doesn't return me the first value of it;s 0th index.

ArrayList<String> arrayList = new ArrayList<String>();
Scanner scan= new Scanner(System.in);
int noInput=scan.nextInt();

for(int i=0; i < noInput/2; i++)
   arrayList.add(scan.nextLine());       

for(int i=0;i<arrayList.size();i++)
   System.out.println("ArrayList:"+arrayList.get(i) + " "  + i );
Maroun
  • 94,125
  • 30
  • 188
  • 241
Sumit Kandoi
  • 427
  • 4
  • 12
  • 1
    The problem is much more likely that you didn't add to the ArrayList what you thought you added. Focus your debug efforts on what is going into the ArrayList. – Patricia Shanahan Jan 21 '15 at 10:42
  • Yeah, i can understand that thing.but still i am not able to identify the problem.can u help me figuring this problem – Sumit Kandoi Jan 21 '15 at 10:43
  • Can you show the error of your code . . . – marsahllDTitch Jan 21 '15 at 10:46
  • possible duplicate of [Scanner issue when using nextLine after nextXXX](http://stackoverflow.com/questions/7056749/scanner-issue-when-using-nextline-after-nextxxx) – Tom Jan 21 '15 at 10:47

3 Answers3

2

Use scan.next() instead of scan.nextLine().

roeygol
  • 4,908
  • 9
  • 51
  • 88
1

Because Scanner#nextInt reads only the int value, then nextLine in the first iteration will consume the remaining \n (the enter you hit after you entered the integer value).

To fix this, add nextLine after nextInt or use next instead of nextInt.

Maroun
  • 94,125
  • 30
  • 188
  • 241
0

It is probably because your list is never filled. I think the first loop isn't gone into, so nothing is added to the array.
for(int i=0; i < noInput/2; i++) arrayList.add(scan.nextLine());

Try debugging it or printing the size of the arraylist

bobK
  • 704
  • 2
  • 7
  • 24