2012-12-04 26 views
-2

我寫了一個方法,它將一個int數組作爲參數,然後返回數組中最大的條目!如何返回Java中最大的數組條目

這就是我所做的,但它沒有奏效!

的唯一錯誤是largest();

The method largest(int[]) in the type Moon is not applicable for the arguments() 

問題是什麼?

public class Moon { 
    public static void main(String[] args {  
     int array1[] = {5,10,15,20,25,30}; 

     int max = largest(); 
     System.out.println("the largest number is : " + max); 

    } 


    static int largest(int array1[]){ 

     int maxValue = 0; 

     for (int i = 0; i < array1.length; i++){ 
      if (array1[i] > array1[maxValue]) maxValue = i;  
     } 
     return maxValue; 
    } 
} 
+3

你沒有將'array1'作爲參數傳遞給你的'最大'方法。技術上編譯錯誤足以解決這類問題。 –

+0

答案說,你應該'返回array1 [maxValue];'因爲你保存索引在maxValue。 – jlordo

回答

2
  1. 呼叫最大通過將數組:

    int max = largest(array1); 
    
  2. 與初始化您maxInteger.MIN_VALUE爲:

    int maxValue = Integer.MIN_VALUE; 
    
  3. 更改你的比較如下:

    if (array1[i] > maxValue)   
        maxValue = array1[i];   
    } 
    
+0

@ user1877061檢查答案。我已經指出了關於最大值邏輯的問題(點2和3)。 –

+0

THX很多,,它的工作...我調整它像你沒有和它的工作原理.. 這樣 靜態INT最大(INT數組1 []){ \t \t \t \t INT包括maxValue = 0; \t \t \t \t for(int i = 0; i 包括maxValue)\t \t \t \t包括maxValue = ARRAY1 [I]; \t \t \t } \t \t \t \t \t \t 返回\t包括maxValue; –

+0

@ user1877061很高興知道。請不要忘記接受你喜歡的答案。 –

1

int max = largest(array1);

而且你的函數:

static int largest(int array1[]){ 

    int maxValue = Integer.MIN_VALUE; 

    for (int el : array1) 
     if (el > maxValue) 
      maxValue = el; 

    return maxValue; 
} 
+0

他們很多人:D 我喜歡那個「int max = largest(array1);」 它工作,但是當我運行代碼時,它將答案設置爲5! 數組中最大的數字是30,怎麼回事!!? –

4

你實際上並沒有傳遞數組作爲參數英寸應該是:

int max = largest(array1); 
2

我看到兩個問題:

  1. 你忘了通過在largest()調用數組。
  2. largest()返回最大值的索引,但調用方將其視爲值本身。