How to arrange an array for odd numbers before even numbers?

0

I'm trying to make a program that arranges an array to put the odd numbers before the even numbers, this was my attempt, which I'm doing wrong.

Code:

    System.out.print("Indique o número de elementos do array: ");
    int a = scanner.nextInt();
    int [] Numbers = new int [a];
    String Numbers_S = "";
    for ( int k = 0; k < a; k++ )
    {
        System.out.print("elemento na posição " + k + " do array: ");
        Numbers [k] = scanner.nextInt();
    }
    for ( int i = 0; i < a; i++ )
    {
        if ( Numbers [i] % 2 != 0 )
        {
            Numbers_S += String.valueOf(Numbers [i]);
        }
        if ( Numbers [i] % 2 == 0 )
        {
            Numbers_S += String.valueOf(Numbers [i]);
        }
    }
    for ( int n = 0; n < a; n++ )
    {
        Numbers [n] = Character.getNumericValue(Numbers_S.charAt(n));
    }
    String New_Numbers = Arrays.toString(Numbers);
    System.out.println(New_Numbers);
    
asked by anonymous 13.11.2018 / 22:00

1 answer

0

Here's a code I've done, I suggest you understand every line written, and if possible, redo it your way! Thus you will have the importunity of exercising.

   //VETOR COM TODOS OS VALORES
    Integer[] todosValores = new Integer[10];
    //VETOR COM OS VALORES IMPARES
    Integer[] valoresImpares = new Integer[5];
    //VETOR COM OS VALORES PARES
    Integer[] valoresPares = new Integer[5];

    //Indices para armazenar os valores no vetor temporario
    int indiceImpar = 0;
    int indicePar = 0;
    int indiceValores =  0;


    //PERCORRENDO TODO O VETOR
    for (int i = 0; i < todosValores.length; i++) {

        //VERIFICANDO SE É IMPAR OU PAR
        if(todosValores[i] % 2 == 0 ){
            valoresPares[indicePar] = todosValores[i] ;
            indicePar++;
        }else{
            valoresImpares[indiceImpar] = todosValores[i] ;
            indiceImpar++;

        }

    }

    //COLOANDO OS NUMEROS IMPARES
    for (int j = 0; j < valoresImpares.length; j++) {
        todosValores[indiceValores] = valoresImpares[j];
        indiceValores++;
    }

    //COLOANDO OS NUMEROS PARES
    for (int j = 0; j < valoresPares.length; j++) {
        todosValores[indiceValores] = valoresPares[j];
        indiceValores++;
    }
    
14.11.2018 / 12:17