Counting an Occurrence in an Array (Java)

后端 未结 12 1737
情歌与酒
情歌与酒 2020-12-16 05:23

I am completely stumped. I took a break for a few hours and I can\'t seem to figure this one out. It\'s upsetting!

I know that I need to check the current element in

相关标签:
12条回答
  • 2020-12-16 06:10
    import java.util.Scanner;
    
    public class array2 {
        public static void main (String[]args) {
            Scanner input = new Scanner (System.in);
            int [] number = new int [101];
            int c;
    
            do {
    
                System.out.println("Enter the integers from 1-100");
                c = input.nextInt();
                number[c]++;
    
            }while (c != 0);
            for(int i = 0; i < number.length ; i++) {
                if (number[i] !=0) {
                    if (number[i] == 1)
                        System.out.println(i + " occurs " + number[i] + " time");
                    else
                        System.out.println(i + " occurs " + number[i] + " times "); 
    
                }
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-16 06:12

    You need to sort the order of your numbers in the array. You can use a 'sort()' method, which will organize your numbers from smallest to biggest.

    You also need two loops, one to compare against the other. Or in my solution's case, I used a 'while statement' and then a 'for loop'.

    I dunno if my method of solving your problem is what you are looking for. Maybe there is a shorter and/or better way to solve this. This is just the way I thought of it. Good luck!

    public static int getOccurrences(int[] numbers){
    
        Array.sort (numbers); //sorts your array in order (i,e; 2, 9, 4, 8... becomes, 2, 4, 8, 9)
    
        int count = 0;
        int start = 0; 
        int move = 0;
    
            while(start < numbers.length){
                for (int j = 0; j < numbers.length; j++){
                    int currentInt = numbers[start];;
                    if (currentInt == numbers[j])
                    {
                        count++;
                        move++;
                    }
                }
                    if(count == 1){
                        return ("Number : " + numbers[start] + " occurs " + count + " time ");
                }   else {
                        return ("Number : " + numbers[start] + " occurs " + count + " times ");
                }
                    count = 0;
                    start = start + move;
                    move = 0;
            }
    }
    
    0 讨论(0)
  • 2020-12-16 06:17

    @NYB You're almost right but you have to output the count value and also start it from zero on each element check.

        int count=0,currentInt=0;
        for (int i = 0; i < numbers.length; i++)
        {
        currentInt = numbers[i];
        count=0;
    
           for (int j = 0; j < numbers.length; j++)
               {
                 if (currentInt == numbers[j])
                    {
                      count++;
                     }
                }
                System.out.println(count);
          }
    

    @loikkk I tweaked your code a bit for print out of occurrence for each element.

    int[] a = { 1, 9, 8, 8, 7, 6, 5, 4, 3, 3, 2, 1 };
    
        Arrays.sort(a);
    
        int nbOccurences = 1;
    
        for (int i = 0, length = a.length; i < length; i++) {
            if (i < length - 1) {
                if (a[i] == a[i + 1]) {
                    nbOccurences++;
                }
            } else {
                System.out.println(a[i] + " occurs " + nbOccurences
                        + " time(s)"); //end of array
            }
    
            if (i < length - 1 && a[i] != a[i + 1]) {
                System.out.println(a[i] + " occurs " + nbOccurences
                        + " time(s)"); //moving to new element in array
                nbOccurences = 1;
            }
    
        }
    
    0 讨论(0)
  • 2020-12-16 06:17

    We can use java 8 Stream API to create Frequency Map

    Stream.of("apple", "orange", "banana", "apple") .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) .entrySet() .forEach(System.out::println);

    The downstream operation is itself a collector (Collectors.counting()) that operates on elements of type String and produces a result of type Long. The result of the collect method call is a Map.

    This would produce the following output:

    banana=1

    orange=1

    apple=2

    0 讨论(0)
  • 2020-12-16 06:19
    package countoccurenceofnumbers;
    
    import java.util.Scanner;
    public class CountOccurenceOfNumbers {
    
    
        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
            int [] num = new int[100]; 
            int [] count = new int[100];
            //Declare counter variable i
            //and temp variable that will
            //temporarily hold the value
            //at a certain index of num[] array
            int i,temp = 0;
            System.out.println("Enter the integers between 1 and 100: ");
    
            //Initialize num[] array with user input
            for(i=0; i < num.length; i++){
                num[i] = input.nextInt();
                //expected input will end when user enters zero
                if(num[i] == 0){
                    break;
                }
            }//end of for loop
    
            //value at a given index of num array 
            //will be stored in temp variable
            //temp variable will act as an index value
            //for count array and keep track of number
            //of occurences of each number
            for(i = 0; i < num.length; i++){
                    temp = num[i];
                    count[temp]++;
                }//end of for looop
    
            for(i=1; i < count.length; i++){
    
                if(count[i] > 0 && count[i] == 1){
                 System.out.printf("%d occurs %d time\n",i, count[i]);
                 }
                else if(count[i] >=2){
                    System.out.printf("%d occurs %d times\n",i, count[i]);
                }
    
    
             }//end of for loop
    
        }//end of main
        }//end of CountOccurrenceOfNumbers
    

    ///////////OUTPUT//////////////////////

    Enter the integers between 1 and 100:
    2 5 6 5 4 3 23 43 2 0
    2 occurs 2 times
    3 occurs 1 time
    4 occurs 1 time
    5 occurs 2 times
    6 occurs 1 time
    23 occurs 1 time
    43 occurs 1 time
    BUILD SUCCESSFUL (total time: 3 minutes 23 seconds)

    0 讨论(0)
  • 2020-12-16 06:22
    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
     // This program counts the number of occurrences of error message. It read the data from Excel sheet for the same.
    public class fileopen {
        public static void main(String[] args) {
    
            String csvFile = "C:\\Users\\2263\\Documents\\My1.csv";
            BufferedReader br = null;
            String line = "";
            String cvsSplitBy = ",";
            List<String> list = new ArrayList<String>();
    
            String[] country = null;
            Map<String, Integer> hm = new HashMap<String, Integer>();
            try {
    
                br = new BufferedReader(new FileReader(csvFile));
                while ((line = br.readLine()) != null) {
    
                    // use comma as separator
                    country = line.split(cvsSplitBy);
    
                    list.add(country[2]);
    
                    System.out.println(country[1]);
                }
                for (String i : list) {
                    Integer j = hm.get(i);
                    hm.put(i, (j == null) ? 1 : j + 1);
                }
                // displaying the occurrence of elements in the arraylist
                for (Map.Entry<String, Integer> val : hm.entrySet()) {
                    if(val.getKey().equals("Error Message")){
                        System.out.println(val.getKey());
                        continue;
                    }
                    System.out.println(val.getKey() + " " + val.getValue());
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (br != null) {
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题