Numbers located in odd positions

2

I should only present the numbers present in the odd positions of the vector, however I'm locked:

package pag1;

import java.util.Scanner;
import java.util.Arrays;

public class ex1 {

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

        int posicao = 0;
        int[] numeros = new int[10];
        System.out.println("Digite 10 números inteiros seguidos:");

        while(posicao <= 9){
          numeros [posicao] = x.nextInt();
          posicao++;
        }

        System.out.println(Arrays.toString(numeros));       
    }

 }

At the time of showing only the numbers that are in the odd positions do not know how, only show all positions of the vector.

    
asked by anonymous 03.07.2017 / 07:43

2 answers

4

Make a loop that starts from position 1 of your array and increments from 2 by 2 to position 7:

import java.util.Scanner;
import java.util.Arrays;

public class ex1 {

    public static void main (String[] args){

        Scanner x = new Scanner (System.in);

        int posicao = 0;
        int[] numeros = new int[10];
        System.out.println("Digite 10 números inteiros seguidos:");

        while(posicao <= 9){
        numeros [posicao] = x.nextInt();
        posicao++;
        }

        for(int i = 1; i < numeros.length; i+=2){
            System.out.println("indice: " + i + " = " + numeros[i]);
        }             
    }    
 }

See working in the ideone: link

Remember that arrays start at index 0, so your array goes from 0 to 9.

    
03.07.2017 / 12:37
2

To show the odd or even value you can use as follows:

valor % 2 == 0 // retorna true para valores pares
valor % 2 != 0 //retorna true para valores impares

Using this expression within a if , it tests the return of the division by two is equal to or different from zero

Your example could have the following solution, using posicao to return all values in odd or numeros[posicao] to return all odd values saved in vector:

Scanner x = new Scanner(System.in);
int posicao = 0;
int[] numeros = new int[10];
while (posicao <= 9) {
   System.out.println("Digite o numero na possição vetor[" + posicao + "]:");
   numeros[posicao] = x.nextInt();
   posicao++;
}

posicao = 0;
while (posicao <= 9) {
    if (posicao % 2 != 0) {
        System.out.println("valor na posição impar do vetor:" + numeros[posicao]);
    }
    posicao++;
}
    
03.07.2017 / 12:43