2016-06-14 47 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)数组,因此这可能是第二个参数
相关问题