简体   繁体   English

计算一个 int 的出现次数

[英]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?如果数组用 {13, 28, 5, 11} 填充,则返回最小值为 5,计数为 1。但是,当数组填充给定数字时,返回计数为 2,而此时计数应为 1 . 我将如何解决这个问题? 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:您应该将计数初始化为 1,并在当前最小值更改时重置为 1:

  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++;
     }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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