Java - Read in 7 integers, count number of reoccurrances

Viewed 68

I am taking an intro Java class and I'm stuck on an assignment. The goal is to write a program using single dimensional arrays that reads in 7 integers and then displays the number of times each value entered reoccurs (i.e. if you enter the number 12 twice, one of the output lines is "Number 12 occurs 2 times.")

I have some of it written already, but I'm stuck at how to count the number of times each array element occurs. I have an idea that I'm going to need a method and a second array, but I've hit a wall:

public class NumOfOccurrIn7 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // Declare scanner and array
        Scanner A = new Scanner(System.in);
        int counter[] = new int[7];
        System.out.print("Please enter 7 numbers: ");

        //Populate initial array
        for(int t = 0; t < 7; t++) {
            counter[t] = A.nextInt();
        }

        //Process # of reoccurences and print results
        for(int t=0; t<7; t++) {


        }


        for(int t=0; t<7; t++) {
            System.out.print("Number " + counter[t] + " occurs " + x + 
                    " times./n");
        }

    }

    public static int CountOccurrance(int counter[]) {

    }

}

Thank you for your feedback!

3 Answers

If the number 12 occurs twice, you don't want the output to print twice, so first you check if the number has already been processed. You do that by iterating over the array elements before t, and if one of them is the same as the current number, you don't print anything.

Next you check the rest of the array and count the number of times the current number occurs, then print the message.

// Process # of reoccurences and print results
for (int i = 0; i < 7; i++) {
    boolean print = true;
    int count = 0;
    for (int j = 0; j < 7; j++) {
        if (counter[j] == counter[i]) {
            if (j < i) {
                print = false;
                break;
            }
            count++;
        }
    }
    if (print) {
        System.out.println("Number " + counter[i] +
                           " occurs " + count + " times.");
    }
}

You can use Collections::frequency to count the occurrences e.g.

import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) {
        int[] nums = { 1, 2, 1, 3, 4, 2, 5, 1, 6, 5, 7, 8, 4, 9 };
        List<Integer> list = IntStream.of(nums).boxed().collect(Collectors.toList());
        Set<Integer> set = new HashSet<Integer>(list);
        for (int n : set) {
            System.out.println("Frequency of " + n + " is " + Collections.frequency(list, n));
        }
    }
}

Output:

Frequency of 1 is 3
Frequency of 2 is 2
Frequency of 3 is 1
Frequency of 4 is 2
Frequency of 5 is 2
Frequency of 6 is 1
Frequency of 7 is 1
Frequency of 8 is 1
Frequency of 9 is 1

Another example of how you can count the duplicates is:

int[] nums = { 1, 2, 1, 3, 4, 2, 5, 1, 6, 5, 7, 8, 4, 9 };
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
boolean duplicatesFound = false;
for (int n : nums) {
    if (map.get(n) == null) {
        map.put(n, 1);
    } else {
        map.put(n, map.get(n) + 1);
        duplicatesFound = true;
    }
}
if (duplicatesFound) {
    System.out.println("Duplicates are as follows:");
    map.entrySet().stream().filter(e -> e.getValue() > 1)
            .forEach(e -> System.out.println(e.getKey() + " has occurred " + e.getValue() + " times."));
} else {
    System.out.println("There are no duplicates in the list");
}

[Update]

Yet another solution (Thanks, @Andreas for the suggestion):

import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        int[] nums = { 1, 2, 1, 3, 4, 2, 5, 1, 6, 5, 7, 8, 4, 9 };
        Map<Integer, Long> frequencyMap = Arrays.stream(nums).boxed()
                .collect(Collectors.groupingBy(n -> n, Collectors.counting()));
        frequencyMap.forEach((n, count) -> {
            System.out.println("Frequency of " + n + " is " + count);
        });
    }
}

Output:

Frequency of 1 is 3
Frequency of 2 is 2
Frequency of 3 is 1
Frequency of 4 is 2
Frequency of 5 is 2
Frequency of 6 is 1
Frequency of 7 is 1
Frequency of 8 is 1
Frequency of 9 is 1
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int counter[] = new int[7];

        System.out.print("Please enter 7 numbers: ");

        for (int t = 0; t < 7; t++) {
            counter[t] = scanner.nextInt();
        }

        int[] occurrances = new int[counter.length];

        label:

        for (int t = 0; t < counter.length; t++) {
            int counterValue = counter[t];

            for (int i = 0; i < t; i++) {
                if (counterValue == counter[i]) {
                    continue label;
                }
            }

            occurrances[t] = 1;

            for (int j = 0; j < counter.length; j++) {
                if (j == t) {
                    continue;
                }
                int other = counter[j];

                if (other == counterValue) {
                    occurrances[t]++;
                }
            }

            if (occurrances[t] > 0) {
                System.out.println("Number " + counter[t] + " occurs " + occurrances[t] + " times.");
            }
        }

    }
Related