简体   繁体   中英

Java. programs counts the occurences of 7 numbers entered by the user in an array

most of my code works, I figured out how to count each number's occurrence in the array. my problem is when I display the information every number is displayed and if that number appears multiple times in the array, the number is displayed multiple times, when the number should really be shown one time with all of its occurrences.

For example

Enter seven numbers: 12 23 44 22 23 22 55
Number 12 occurs 1 times
Number 23 occurs 2 times
Number 44 occurs 1 times
Number 22 occurs 2 times
Number 23 occurs 2 times
Number 22 occurs 2 times
Number 55 occurs 1 times

22 and 23 are displayed multiple times, when they should only be shown once.

import java.util.Scanner;
public class CountOccurrences {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        //Variables, arrays, and objects declaration and initialization
        Scanner input = new Scanner(System.in);
        int[] numbers = new int[7];
        int[] copy = new int[7];
        int number = 0;
        int count =0;
        //Prompts user for 7 numbers
        System.out.print("Enter seven numbers: ");
        //For loop initializates arrays numbers and copy with the 7 number typed
        //in by the user, resulting in two identical arrays.
        for (int i = 0; i < 7; i++){
        numbers[i] = input.nextInt();
        }

        for (int i = 0; i < numbers.length; i++){
           number = numbers[i];

           for (int j = 0; j < 7; j++){
               if (number == numbers[j]){
               count ++;
               }
           }  
            System.out.println("Number " + number + " occurs " + count + " times");
            count = 0;
        }

     } 
}
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int[] numbers = new int[7];
    System.out.print("Enter seven numbers: ");

    // accept the input
    Arrays.setAll(numbers, i -> input.nextInt());

    // iterate only on distinct values and print the occurrences
    // this will save you a lot of time if you have a lot of duplicates in your array
    Arrays.stream(numbers).distinct().forEach(i -> {
        int f = getFrequency(numbers, i);
        if (f > 1) System.out.println("Number: " + i + " appears " + f + " times.");
    });
}

private static int getFrequency(int[] numbers, int n) {
    // get count of the number in the array
    return (int) Arrays.stream(numbers).filter(num -> n == num).count();
}

An example using java-streams. It saves you from creating a lot of variables and use the in-built features. The less code there is, the less places there are for bugs to lurk.

You can use a Set to store only unique numbers from the user's input. To preserve the order of the input, you could use a LinkedHashSet . Also, your count variable should be inside your for loop so that the count of previous numbers does not carry over to each subsequent iteration without you having to reset the count to 0 at the end of each iteration.

public static void main(String[] args) {
    //Variables, arrays, and objects declaration and initialization
    Scanner input = new Scanner(System.in);
    final int[] numbers = new int[7];
    //Prompts user for 7 numbers
    System.out.print("Enter seven numbers: ");
    //For loop initializates arrays numbers and copy with the 7 number typed
    //in by the user, resulting in two identical arrays.
    final Set<Integer> uniqueNums = new LinkedHashSet<>();
    for (int i = 0; i < 7; i++){
       numbers[i] = input.nextInt();
       uniqueNums.add(numbers[i]);
    }

    for (final int number: uniqueNums){
        int count =0;

       for (int j = 0; j < 7; j++){
           if (number == numbers[j]){
           count ++;
           }
       }  
        System.out.println("Number " + number + " occurs " + count + " times");
    }

 } 

Without Set , you can implement a indexOf method and use it to check if an element in the array is the first occurrence of said element.

public static void main(String[] args) {
    //Variables, arrays, and objects declaration and initialization
    Scanner input = new Scanner(System.in);
    int[] numbers = new int[7];
    int[] copy = new int[7];
    int number = 0;
    int count =0;
    //Prompts user for 7 numbers
    System.out.print("Enter seven numbers: ");
    //For loop initializates arrays numbers and copy with the 7 number typed
    //in by the user, resulting in two identical arrays.
    for (int i = 0; i < 7; i++){
    numbers[i] = input.nextInt();
    }

    for (int i = 0; i < numbers.length; i++){
       number = numbers[i];
       if(indexOf(numbers, number) != i) continue;

       for (int j = 0; j < 7; j++){
           if (number == numbers[j]){
           count ++;
           }
       }  
        System.out.println("Number " + number + " occurs " + count + " times");
        count = 0;
    }

 }

private static int indexOf(final int[] arr, final int num){
    for(int i = 0; i < arr.length; i++){
        if(arr[i] == num) return i;
    }
    return -1;
}

The entire task (other than a little setup code) can be done in one statement:

Scanner input = new Scanner(System.in);
System.out.print("Enter seven numbers: ");
Stream.generate(input::nextInt).limit(7)
        .collect(groupingBy(identity(), counting()))
        .forEach((n, c) -> System.out.println("Number " + n + " occurs " + c + " times"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM