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);
}
}
}
}
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.
– pmargreff
@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.
– Caffé