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

Asked

Viewed 850 times

0

I’m trying to make a program that organizes an array to put the odd numbers before the even numbers, this was my attempt, what 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);
  • And what problem does the code present ? It does not give the result you expect ? It gives error ? The goal is to manipulate the array directly ? Because the concatenation with the String ?

1 answer

0


Follow a code I made, I suggest you understand every written line, and if possible redo it your way! So you will have the importunity to exercise.

   //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++;
    }

Browser other questions tagged

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