2014-10-20 99 views
0

嘿我试图调用一个方法 “swapPairs(INT [] NUMS)”,但我得到了多个错误错误时调用方法

- Syntax error on token "{", delete this token 
- The method swapPairs(int[]) in the type ArrayMethods is not applicable 
    for the arguments (int, int, int, int) 
- Syntax error on token "swapPairs", @ expected before this token 
- Syntax error on token ";", @ expected after this token 
- Syntax error on token "}", delete this token" 

这是我的代码:

public class ArrayMethods { 
    public static void main(String[]args){ 
     System.out.println(swapPairs({5,4,2,6})); 
     allLess({5,4,3}, {4,7,5}); 
    } 
    public boolean allLess(int[] nums, int[] num){ 
     int c=0; 
     if(nums.length==num.length){ 
      for(int i=0; i<num.length; i++){ 
       if(nums[i]<num[i]) 
       return true; 
      } 
     } 
     return false; 


    } 
    public int[] swapPairs(int[] nums){ 
     int[] x=new int[nums.length]; 
     if(nums.length%2==0){ 
      for(int i=0; i<nums.length; i++) 
       x[i]=nums[i+1]; 
      return x; 
     } 
     else 
      for(int i=0; i<nums.length-1; i++) 
       x[i]=nums[i+1]; 
     return x; 

    } 
    public void printArray(int[] nums){ 
     for(int i=0; i<nums.length; i++) 
      System.out.println(nums[i]); 
    } 



} 

在swapPairs方法中,我可能也有一个错误。它的目标是交换数组中的相邻元素,并且如果数组的长度是奇数,则将最后一个元素保留在它所在的位置。谢谢!

回答

3

您不能从static类访问non-static成员。

System.out.println(swapPairs({5,4,2,6})); // swapPairs() is non-static 
allLess({5,4,3}, {4,7,5}); //allLess() is non-static 

解决方案:

使ArrayMethods一个实例来访问swapPairs()方法和allLess()方法,或这些方法static

但是这里还有更多的问题。不能使用swapPairs({5,4,2,6})你必须使用swapPairs(new int[]{5,4,2,6})

一种修正方法

ArrayMethods arrayMethods = new ArrayMethods(); 
System.out.println(arrayMethods.swapPairs(new int[]{5, 4, 2, 6})); // * 
arrayMethods.allLess(new int[]{5, 4, 3},new int[]{4, 7, 5}); 

注重*线。你明确地打电话给toString()。这不是一个好习惯。

更多的问题:

for (int i = 0; i < nums.length; i++) 
    x[i] = nums[i + 1]; // you will get ArrayIndexOutOfBoundsException 
    return x; 

i=nums.length-1nums[i + 1]将成为num[nums.length]。现在阵列中没有这样的索引。如果数组的大小为4,则只有从03的索引。

您可以将这些观点记录到您的帐户并使这些错误正确。

+0

非常感谢! – nebularis 2014-10-20 04:10:56

+0

@nebularis欢迎您。 – 2014-10-20 04:11:27