Increase the index in the for each

0

In this case I am filling an array with random numbers. When I use a normal for the index in each iteration increases one by one, but with the for each I can not do that.

I attach the code

 Scanner lector = new Scanner(System.in);

    int nro;

    System.out.println("Digite  la cantidad de numeros con la que quiera llenar el arreglo de forma aleatoria");
    nro = lector.nextInt();

    int a[] = new int[nro];


   /* for(int i = 0; i < nro; i++){

     a[i] = (int) (Math.random()*100);   

        System.out.println("Indice " + i + " es igual " + a[i]);

    }*/



      for(int i : a){

       a[i] = (int) (Math.random()*100);   

      System.out.println("Indice "+ (1+i)  + " = " + a[i]);    

    }
    
asked by Tiago Viezzoli 24.11.2018 в 22:26
source

1 answer

1

The problem is that in that for the variable i does not have every position, but it has the content of each position, that is, if your vector is [1,6,3], the variable i will have the value 1, 6 and 3 in each iteration. In conclusion, for this exercise the for(int i: a) does not work, you must use the for(int i = 0; i < nro; i++) . Good luck!

    
answered by 24.11.2018 в 23:48