check elements does not work

Asked

Viewed 43 times

0

I want to do a method that will check if an element has already been added to a list, if it will already increment 1. This is the class I made, but it is a mistake.

public class Rascunho {

    private int [] vetor;
    private int countValor ;
    private int c = 0;

        public Rascunho () {
            vetor = new int [7];
            countValor = 0;
        }

        public void insertValor (int valor) {
            countValor ++;
            int i = 0; 
            vetor [i] = valor;
        }

        public int verificar () {
            for (int i = 0; i<countValor-1; i++)
                for (int j= 0; j < countValor; j++) {       
                    if (vetor[j+1] == vetor[i]) {c++;}
                }
            return c;
        }
    }

1 answer

0

The method to insert value is always inserting at position 0. The method to check, checks more than once the same value.

   public void insertValor (int valor) {
        countValor ++;
        vetor [countValor-1] = valor;
    }

   public int verificar () {
        for (int i = 0; i<countValor-1; i++)
            for (int j = i+1; j < countValor; j++) {       
                if (vetor[j] == vetor[i]){
                    c++;
                }
            }
        return c;
    }

Browser other questions tagged

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