2014-10-20 103 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