Adding values to an array in java

-3

int[] tall = new int[28123];

for (int j = 1;j <= 28123; j++){
    int x = 0;
    tall[x] = j;
    x++;
}

What is wrong with this code? Shouldn't this code do the following:

  1. Create an array named tall with a size of 28123.
  2. Make index 0 = 1, index 1 = 2 and so on.

This question is tagged with java arrays

~ Asked on 2013-03-17 21:03:52

The Best Answer is


4

No, you're re-initializing x in every loop. Change to:

int[] tall = new int[28123];
int x = 0;

for (int j = 1;j<=28123;j++){
    tall[x] = j;
    x++;
}

Or, even better (since x is always equal to j-1):

int[] tall = new int[28123];

for (int j = 1;j<=28123;j++){
    tall[j-1] = j;
}

~ Answered on 2013-03-17 21:05:06


1

You have not one, but many mistakes. It should be:

int[] tall = new int[28123];

for (int j=0;j<28123;j++){
    tall[j] = j+1;
}

Your code is putting a 0 in all the positions of the array.

Morover, it'll throw an exception, because the last index of the array is 28123-1 (arrays in Java start in 0!).

~ Answered on 2013-03-17 21:08:29


Most Viewed Questions: