2016-06-14 25 views
-3

我是java新手,正在尋找一些建議。我被分配到下面的問題,我不能讓比較方法來運行我的生活。它不會編譯。我收到以下錯誤:Java新手,y類中的方法X無法應用

error: method compare in class Plateau cannot be applied to given types;                       
     compare(a[N]); 
required: int[],int                                          
    found: int                                            
    reason: actual and formal argument lists differ in length 

任何幫助將不勝感激。

1.4.21最長的高原。給定一個整數數組,找出最長連續的等值序列的長度和位置,其中緊接在該序列之前和之後的元素值較小。該數組應該傳遞給一個方法,結果應該被打印到屏幕上。

public class Plateau{ 
    public static void main(String[] args) { 
    int N = args.length; 
    int[] a = new int [N]; 

     for (int i=0; i < N; i++){ 
      int number = Integer.parseInt(args[i]); 
      a[i]=number; 
     } 
     compare(a[N]); 
    } 

    public static void compare(int[] a, int N){ 
    int comp = a[0]; 
    int current_length=0; 
    int max=0; 
    int maxlength=0; 

     for(int l=0; l < N; l++){ 
     if (a[l] > comp){ 
     current_length = 0; 
     comp = a[l]; 
     max = a[l]; 
     } 

     if (a[l] == comp){ 
      current_length+=1; 
      comp = a[l]; 
     } 
     else if (a[l] < comp && a[l] < max){ 
     comp = a[l-1]; 
     current_length=maxlength; 
      l++; 
     } 
     } 

     System.out.println(max); 
     System.out.println(maxlength); 
    } 
} 
+2

嘗試'compare(a,N);' – Berger

+0

'compare(int [] a,int N)'需要2個參數,但用1個參數調用compare(a [N])'。從任何初學者入門(語言無所謂) – john

回答

2

這是非常明顯的:參數需要一個數組和一個值(長度?索引),但你只是從數組中傳遞一個值。

只要打開

compare(a[N]); 

compare(a, N); 
+0

謝謝!我沒有意識到,一旦我宣佈[],我可以參考它作爲簡單的 –

0

你的方法簽名不你想調用的方式相匹配。在你的主要方法中,你試圖調用一個叫做compare的方法,它接受一個整數數組,但唯一的定義是使用一個整數數組和一個整數的比較方法。用法和定義需要保持一致,否則編譯器將不知道你在做什麼。

0

你的方法

public static void compare(int[] a, int N){ 

有兩個參數一個是整數數組,另一個是整數

當你調用這個方法在你的主要方法,你只傳遞一個參數

public static void main(String[] args) { 
    int N = args.length; 
    int[] a = new int [N]; 

     for (int i=0; i < N; i++){ 
     int number = Integer.parseInt(args[i]); 
     a[i]=number;} 
    compare(a,N); // pass a integer along with your integer array (you have to use your array variable which is a and not a[N]) 
    } 

這就是爲什麼你得到的錯誤傳遞一個整數一起,它會工作 也你錯誤地傳遞數組

int[] a = new int [N]; 

已這裏聲明陣列並因此需要傳遞變量a,而不是[N]

2

問題是與參數和方法簽名的問題。正如我看到你正在學習,我不會給你一個完整的解決方案。我只會指向你的方式來解決它

  1. compare需要兩個參數int[] a, int N,但你只能用一個compare(a[N])
  2. a[N]調用它的方法是錯誤的,因爲它會指標外的元素陣列(注意,數組索引從0至N-1)
  3. a是int []類型的數組,所以需要使用此作爲呼叫的第一個參數compare
  4. N是多少元素(類型爲int)數組,因此這可能是第二個參數
相關問題