Decision problem within an array loop

Asked

Viewed 64 times

-1

My problem is in the second if, what I was actually trying to do was to determine that at the time the loop was passing through position 11 of the array it would add the " n", but the way I did it, it does it in all loops, not just in the position I want. I understand my mistake, but I don’t know how to do it properly.

  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
  • 2

    Hi, Adrian, next time enter the line with a comment // <----------- LINHA 22. Putting the numbering here makes the copy/Paste for testing complicated.

1 answer

1


This is 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
...
  • Although in all positions the check will be performed even if it has already achieved the desired one. This can be improved...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.