[Solved] How to use an array created in a loop outside the loop (java)


In order to access the elements that you have entered into an array you have to indicate the index (position) where the element is. For example, if you have an array with three elements (10, 11 and 12) like this one:

    int[3] array; //<-- Important that this line is outside the while loop
    int i = 0;

    while(i<3) {  //<-- We use number three because the array has 3 elements
        int[i] = 10+i;
    }

In order to obtain the number 10 you have to access the first position of the array, that is position 0:

    int numberTen = array[0];

Here is an example of how to print all the numbers:

    System.out.println(array[0]);
    System.out.println(array[1]);
    System.out.println(array[2]);

You can also use a loop to do that:

    int j = 0;
    while(j<3) {
        System.out.println(array[j]); 
    }

DANGER: if you try to access the position 3 you will have an IndexOutOfBounds Exception because the last position of this array is position 2, as the first one is position 0. That is why in the condition of the while loop you have to use the operator < instead of <=.

solved How to use an array created in a loop outside the loop (java)