2017-10-16 83 views
-2

這是一個簡單地返回最小值及其在數組中出現的次數的程序。如果數組填充{13,28,5,11},則它將min分數返回爲5,將count數返回爲1.但是,當數組填充給定數字時,它將計數返回爲2,當它應該爲1 。我會如何解決這個問題?三江源計算int的出現次數

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

需要重啓'當你發現一個新的最小數count'。 – azurefrog

+1

http://idownvotedbecau.se/nodebugging/ – lexicore

+0

[什麼是調試器,它如何幫助我診斷問題?](https://stackoverflow.com/q/25385173/5221149) – Andreas

回答

3

你應該初始化數爲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++; 
    } 
    }