nebularis
nebularis

Reputation: 9

Error when calling method

Hey I am trying to call a method "swapPairs(int[] nums)", but I am getting multiple errors

 - 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"

This is my code:

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]);
    }



}

In the method swapPairs I might also have an error. The goal of that is to swap adjacent elements in an array, and if the length of the array is odd then to keep the last element where it is. Thanks!

Upvotes: 0

Views: 73

Answers (1)

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35547

You can't access non-static members from a static class.

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

Solution:

Make a instance of ArrayMethods to access the swapPairs() method and allLess() method or make these method static.

But there are more issues here. You can't use swapPairs({5,4,2,6}) you have to use swapPairs(new int[]{5,4,2,6})

One corrected way

 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});

Pay attention to * line. You are calling toString() explicitly. This is not a good practice.

More issues:

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

When i=nums.length-1, nums[i + 1] will become num[nums.length]. Now there is no such index in the array. If the size of the array is 4, You have indexes from 0 to 3 only.

You can take these points to your account and make these mistakes correct.

Upvotes: 3

Related Questions