Problem with decision inside the loop of an array

-1

My problem is in the second if, what I was actually trying to do was to determine that by the time the loop was going through position 11 of the array it added the "\ n", but in the way I did, it does it in all loops, not just in the position I want. I already understood my error, but I do not know how to do it correctly.

  package gerarOrganizar;
  import java.util.*;
  //import java.util.Arrays;
  //import java.util.Collections;
  //import java.util.Random;
  import static javax.swing.JOptionPane.*;
  public class GerarOrganizar {


    public static void main(String[] args) {
        Integer[] array = new Integer[20];
        Random gerador=new Random();
        String aux="";
        for(int i=0;i<20;i++){
            array[i]=gerador.nextInt(50);
            if(array[i]==0)//descarta números = 0
                i--;
        }//for de geração de valores

        aux=String.format("Antes \n");
        for(int i:array){//percorre todo o array retornando o valor para i
            if(array[11]!=null)//este aqui é o problema
                aux=String.format(aux+"\n");
            aux=String.format(aux+"\t %d",i);
    }//fim do for

        showMessageDialog(null,aux);//imprime a ordem gerada

        Arrays.sort(array,Collections.reverseOrder());
        /*sort decide a ordem númerica em ordem decrescente devido ao Collections.reverseOrder*/

        aux=String.format("Depois");
            for(int i:array){/*percorre array retornando os valores para i*/
                aux=String.format(aux+"\n %d",i);/*copia os valor do array na string*/
            }//fim do for

        showMessageDialog(null,aux);//imprime a ordem
    }//main

 }//class
    
asked by anonymous 16.10.2014 / 06:25

1 answer

1

This happens because in all interactions in the cycle in question, position 11 in the vector is different from null .

You can solve it like this:

...
for(int i; i<array.lenght; i++){//percorre todo o array retornando o valor para i
   if( i == 11 ){
         aux=String.format(aux+"\n");
   }
   aux=String.format(aux+"\t %d",array[i]);
}//fim do for
...
    
16.10.2014 / 10:03