brobee brobee - 4 months ago 11
Java Question

Populate an array within a specific range

I wanna populate an array with integers within 2000-3000.

public static void main(String[] args) {

int[] nums = new int[1000];
for (int y = 0; y < nums.length; y++) {

for (int i = 2000; i < 3000; i++) {
nums[y] = i;
}
}
System.out.println(Arrays.toString(nums));
}


I got an array with full of 2999.

What's the problem? Thank you in advance!

TDG TDG
Answer

you're populating the same cell again and again. Your array size is 1000, but your range is 1001: 3000 - 2000 + 1 = 1001

public static void main(String[] args) {

    int[] nums = new int[1001];
    for(int y=0;y<nums.length;y++) {
        nums[y]= y + 2000;
    }

    System.out.println(Arrays.toString(nums));
}