jeudi 28 décembre 2017

Array for loops and RNG in Java

I'm attempting to write a simple for loop that generates three integers and assigns each value to an array index. The second for loop in my code returns unexpected results. Can someone explain to me what's going on?

import java.util.Random;

public class Main {

public static void main(String[] args) {

    //variables
    int[] array = new int[3];
    Random rand = new Random();

    //all else

    for(int item : array) {                     
            array[item] = rand.nextInt(100)+1;
            System.out.println(array[item]);                                
    }       

    System.out.println("\n " +  array[0] + " " + array[1] + " " + array[2]);

    for(int i = array.length; i > 0; i--){
        System.out.println(array[i-1]);         
    }       

}

}




Aucun commentaire:

Enregistrer un commentaire