Dúvida na hora de printar laço de repetição

2 respostas Resolvido
java
Jonathan_Miritz

public static void main(String[] args) {
Scanner tec = new Scanner(System.in);

int [] vetorX = new int [10];
    int [] vetorY = new int [10];
    int [] vetorR = new int [20];
    
   int i, j, x;
   
   System.out.println("Vetor X");
   for (i = 0; i < vetorX.length;i++){
       System.out.print("Informe o "+(i +1)+"º número: ");
       vetorX[i] = tec.nextInt();
   }
   
   
   System.out.println("Vetor Y");
   for (j = 0; j < vetorY.length;j++){
       System.out.print("Informe o "+(j +1)+"º número: ");
       vetorY[j] = tec.nextInt();
   }
   
   
   for (x = 0; x < vetorR.length; x++){
        for (i = 0; i < vetorX.length; i++){
            for (j = 0; j < vetorY.length; j++){
                if(vetorR[x] % 2 != 0){
                    vetorR[x] = vetorX[i];   
                }
                if(vetorR[x] % 2 == 0){
                    vetorR[x] = vetorY[j];   
                }
                System.out.println(vetorR[x]);
            }
        }
   }
}

O problema está na lógica da linha de print, eu acredito… nessa lógica quero pegar os valores de X e Y e alterna-los entre ímpares e pares dentro de R, porém, fiz alguma coisa errada…

2 Respostas

vicentingr
Solucao aceita
for (x = 0, i = 0, j = 0; x < vetorR.length; x++){
            if(x % 2 != 0){
                vetorR[x] = vetorX[i++];
            }
            else {
                vetorR[x] = vetorY[j++];
            }
            System.out.println(vetorR[x]);
 }
Jonathan_Miritz

Percebi que o erro era utilizar o vetor na condição do If, mas o certo era o indice…

Valeu! Não conhecia esse modo de utilizar os indices todos dentro de um for só…

Criado 6 de abril de 2020
Ultima resposta 7 de abr. de 2020
Respostas 2
Participantes 2