-1

I am doing a school task on ArrayLists and Wrapper classes. I have to initialize a for loop, which should fill the ArrayList up with the numbers 1 to 99.

ArrayList<Integer> list = new ArrayList<Integer>();
for(int i = 1; i < 100; i++){
   list.add(i);
   System.out.println(list.get(i));
}

The code until the for-loop body is given in the task.

If I run the code, I get an IndexOutOfBounds Exception.

What can I modify to be able to run the loop?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
ana
  • 97
  • 7

3 Answers3

2

Indexes of list start from 0. So your elements would be from 0 - 99 and not from 1 - 100. access them using list.get(i-1)

Ghost
  • 735
  • 5
  • 16
1

Modify your code as System.out.println(list.get(i-1)); because index start from 0.

h3t1
  • 1,126
  • 2
  • 18
  • 29
ravikj17
  • 9
  • 1
1

An array begins always with the index 0. In almost every languages

ArrayList<Integer> list = new ArrayList<Integer>();
for(int i = 1; i < 100; i++){
   list.add(i);
   System.out.println(list.get(i-1));
}

or

ArrayList<Integer> list = new ArrayList<Integer>();
for(int i = 0; i < 99; i++){
   list.add(i+1);
   System.out.println(list.get(i));
}