Java - Read in 7 integers, count number of reoccurrances

Max091 :

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!

Andreas :

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.");
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=17821&siteId=1