Return vector of integers in java

Asked

Viewed 6,363 times

2

I’m trying to read an array of integers and return the number of ones and the number of zeros, but it always returns at least a zero number, even without me having entered it. Debugging the code, even at the time of reading, if I enter with 5 times the number "one" it only shows how filled with the number one the first house, and yet, counts four. The same thing for debugging in the method contum. I wonder if my mistake is in the function that makes the reading or in the function that counts, grateful.

import java.util.Scanner; //importa classe scanner para fazer a leitura do teclado

/**
 * link : https://www.urionlinejudge.com.br/judge/pt/problems/view/1329
 * @author pmargreff
 */
class Main {

    //método para ler o vetor
    public static int[] leVetor(int tamanho) {
        Scanner teclado = new Scanner(System.in);
        int[] vetor = new int[tamanho];
        for (int i : vetor) {
            vetor[i] = teclado.nextInt();
        }

        return vetor;
    }

    public static int contZero(int[] vetor) {
        int total = 0;
        for (int i: vetor){
            if (vetor[i] == 0)
                total++;
        }
        return total;
    }

    public static int contUm(int[] vetor) {
        int total = 0;
        for (int i: vetor){
            if (vetor[i] == 1)
                total++;
        }
        return total;
    }

    public static void main(String[] args) {
        Scanner teclado = new Scanner(System.in); //inicializa teclado como leitura padrão para entrada
        int tamanho = 1; // váriavel que conterá o tamanho total do vetor
        int vetor[]; //vetor onde irá ficar armazenado os resultados da jogada
        int zero, um; //contém o número de vitória referente a cada um

        while (tamanho != 0) {

            tamanho = teclado.nextInt(); //le o tamanho do vetor

            if (tamanho > 0) {
                vetor = new int[tamanho];   //inicializa variáveis com o espaço necessário na memória 
                vetor = leVetor(tamanho); //le o vetor e salve nele próprio
                zero = contZero(vetor);
                um = contUm(vetor);
                System.out.println("Zeros: " + zero);
                System.out.println("Uns: " + um);
            }
        }
    }
}

1 answer

4


The problem is in the way you change the array. See:

for (int i : vetor) {
   vetor[i] = teclado.nextInt();
}

The above code is getting each value in the array and then using this value as the index. It turns out that array index is one thing and the value in that index is another. You just initialize the array with integer X. Each integer (int) was initialized by Java at zero. So in your first loop, you’re setting X times the value at zero index, each new value overwrites the previous, always at zero index.

Try going through your arrays ("vectors") like this:

for (int i = 0; i < vetor.length; i++) {
    vetor[i] = teclado.nextInt();
}

In the above code the value of i is incremented with each iteration in the loop and up to the last element in the array; and then i is used as an index to change the elements of this same array.

  • Hello, I solved this way, I was using for (int i : vector) for having read n in an article, about the new functions from java 1.5 (if I’m not mistaken), and from what I had understood this way of reading the vector would go through the same from beginning to end. I must have been flawed in interpreting the documentation. Thank you, forgive the misunderstanding.

  • 1

    @pmargreff The loop for that you wore was not wrong - it is valid and useful to go through a collection like this. The problem was that you used the value of the item as if it were the index item in the collection. I tried to make this clear in my reply.

Browser other questions tagged

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