简体   繁体   中英

Count the number of occurrences of an int

This is a program to simply return the min value and the number of time it occurs in the array. If the array is filled with {13, 28, 5, 11} it returns the min as 5 and the count as 1. However, When the array is filled with the given numbers it returns the count as 2, when it should be 1. How would I fix this? Thankyou

public class Test4{
   public static void main(String[] args){
      int[] array = {4, 20, 30, 4, 25, 25, 6, 2, 29, 27, 1, 29, 11, 6, 10, 17, 8};
      findMin(array);
   }

   public static void findMin(int[] array) {
      if (array == null || array.length < 1)
         return;
      int count = 0;
      int min = array[0];

      for (int i = 1; i <= array.length - 1; i++) {

         if (min > array[i]) {
            min = array[i];  
            if(min == array[i]){

               count++;
            }
         }
      }
      System.out.println("The minimum is: " + min +"\n" + "The count is: " + count);
   }
}

You should initialize the count to 1 and reset is to 1 whenever the current min value is changed:

  int count = 1; // initial count should be 1
  int min = array[0];

  for (int i = 1; i <= array.length - 1; i++) {
     if (min > array[i]) {
        // new minimum - reset count to 1
        min = array[i];
        count = 1;
     } else if (min == array[i]) {
         // same minimum - increment count
         count++;
     }
  }

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