Number of repeats within an array

Asked

Viewed 2,086 times

0

I’m trying to count how many times an element appears within an array.

`   
    public static void main(String[] args) {        
    Scanner scan = new Scanner(System.in);
    int[] array = new int[4];
    int a;

    for(int i = 0; i < array.length; i++){
        System.out.println("Digite um numero: ");
        a = scan.nextInt();
        array[i] = a;
    }
    System.out.println("Seu array ficou: " + Arrays.toString(array));
        int vezes = 0;
        for(int i = 0; i < array.length; i++){
                for(int j = 0; j < array.length; j++){
                        if(array[i] == array[j] && i!=j){
                            int numero = array[i];
                            vezes++;
                            while(array[i]==array[j] && vezes>1){
                                System.out.println("O numero "+numero+" é repetido "+vezes+" vezes.");
                                vezes=0;
                            }
                        }
                }
        }
}`

In this example I can only make it show elements that repeat 2 times correctly, this happens because I equal times=0 when it repeats more than once. How can I make sure he doesn’t fall in while(array[i]==array[j] && vezes>1) until you go through all the repeated elements? You can use an "if" too.

If filled with the numbers 1,1,1,2 for example already wrong.

  • Kind of confusing to understand. Try to post what would be the output of your algorithm here to facilitate understanding.

1 answer

1


To work you could only print after performing all the accounting. To do this, you would need to save everything you counted and then just print the variable that stored those accounts. A possible solution would be to adjust your code to the following:

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int[] array = new int[4];
    List<Integer> numerosJaContabilizados = new ArrayList<Integer>();
    Map<Integer, Integer> numeroRepeticoes = new HashMap<Integer, Integer>();
    int a;

    for (int i = 0; i < array.length; i++) {
        System.out.println("Digite um numero: ");
        a = scan.nextInt();
        array[i] = a;
    }
    System.out.println("Seu array ficou: " + Arrays.toString(array));
    for (int i = 0; i < array.length; i++) {
        for (int j = 0; j < array.length; j++) {
            if (array[i] == array[j] && i != j && !numerosJaContabilizados.contains(array[i])) {
                registrarNumeroRepeticao(array[i], numeroRepeticoes);
            }
        }
        numerosJaContabilizados.add(array[i]);
    }
    for (Entry<Integer, Integer> numeroRepeticao : numeroRepeticoes.entrySet()) {
        System.out.println(
                "O numero " + numeroRepeticao.getKey() + " é repetido " + numeroRepeticao.getValue() + " vezes.");
    }
}

private static void registrarNumeroRepeticao(int numero, Map<Integer, Integer> numeroRepeticoes) {
    if (numeroRepeticoes.get(numero) != null)
        numeroRepeticoes.put(numero, numeroRepeticoes.get(numero) + 1);
    else
        numeroRepeticoes.put(numero, 2);
}

The changes made:

  1. Added a variable to store repetitions of numbers: numeroRepeticoes. Notice that it is a map because there you can use as key the number and as value the repetitions.
  2. Added a variable to account for the numbers already processed: Computerized numbers. Your print while would be more or less for this, but the logic would break if the repeated number did not come in sequential order. For this it is best to use a variable that stores these accounts and is used to check whether the number should be accounted for or not.
  3. Added printing of values OUT of loops. So you will print the result only after processing everything.

That was an example of how your method would work, but here are some suggestions:

  1. Refactor the method: Your main method has many responsibilities, the ideal was to divide them at least among different methods. For example, one responsibility could be the reading of the data, the other would be the counting of repetitions and the other would be the printing of repetitions. It is an interesting exercise to try to modularize to the maximum one method. I recommend ;)
  2. Use the Collections API: I saw that you use arrays with primitive types but then you lose the power that the Collections API gives you! Even using it you would solve your problem in a few lines of code, but then it would not be very didactic so it is better to try to implement the logic from scratch same.

I hope I’ve helped ^^

  • 10/10. I would only give one more suggestion to the author of the question. Make a greater commitment to the nomination, as @Giuliana did. So it’ll be more organized and you won’t have to worry about what goes where.

Browser other questions tagged

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