【问题标题】:Error when calling method调用方法时出错
【发布时间】:2014-10-20 03:53:07
【问题描述】:

嘿,我正在尝试调用方法“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 中我也可能有错误。这样做的目的是交换数组中的相邻元素,如果数组的长度是奇数,则将最后一个元素保留在原处。谢谢!

【问题讨论】:

    标签: java arrays eclipse oop


    【解决方案1】:

    您无法从 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-1 时,nums[i + 1] 将变为num[nums.length]。现在数组中没有这样的索引。如果数组的大小为4,则只有从03 的索引。

    您可以将这些积分记入您的帐户并纠正这些错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-31
      • 1970-01-01
      • 2015-01-30
      • 2012-05-09
      • 1970-01-01
      相关资源
      最近更新 更多