Irina Farcau
Irina Farcau

Reputation: 167

errors array integers sum of elements java

I can't find what the error is telling me here:

class Ideone {
public static void main (String[] args) throws java.lang.Exception
{
    twoSum({2,4,7},9);
}
public static int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
    for (int j = i + 1; j < nums.length; j++) {
        if (nums[j] == target - nums[i]) {
            return new int[] { i, j };
        }
    }
}
throw new IllegalArgumentException("No two sum solution");
}
}

The errors are:

Main.java:12: error: illegal start of expression
    twoSum({2,4,7},9);
           ^
Main.java:12: error: ';' expected
    twoSum({2,4,7},9);
            ^
Main.java:12: error: illegal start of expression

I think the declaration is good, so how to change in order this function to work?

Upvotes: 1

Views: 120

Answers (4)

your code is not compiling nor running because you have two errors;

Syntax error on token "twoSum", @ expected before this token

which means that this call

 twoSum({2,4,7}, 9);

is not valid in java, you need to pass a new anonymous int array:

twoSum(new int[]{2,4,7}, 9);

the 2nd error is:

This method must return a result of type int[]

because the method twosum is returning ONLY if this condition is met,

if (nums[j] == target - nums[i]) {
    return new int[]{ i, j };
}

but you need to modify a little the logic and guaranty that the method ALLWAYS returns an int[]

Upvotes: 0

Adnan Isajbegovic
Adnan Isajbegovic

Reputation: 2307

Here you go:

  class Ideone {
    public static void main (String[] args) throws java.lang.Exception
    {
        twoSum(new int[] {2,4,7},9);
    }
    public static int[] twoSum(int[] nums, int target) {
    for (int i = 0; i < nums.length; i++) {
        for (int j = i + 1; j < nums.length; j++) {
            if (nums[j] == target - nums[i]) {
                return new int[] { i, j };
            }
        }
    }
    throw new IllegalArgumentException("No two sum solution");
    }
    }

You need to create an array object, so its twoSum(new int[] {2,4,7},9);. You have done it in the function when you return: return new int[] { i, j }; You must do the same thing in main function.

Upvotes: 0

MikeCAT
MikeCAT

Reputation: 75062

Pass an array instead of writing something illegal by changing

twoSum({2,4,7},9);

to

twoSum(new int[]{2,4,7},9);

Upvotes: 2

Eran
Eran

Reputation: 393781

{2,4,7} can only be used in the declaration of an array, such as :

int[] arr = {2,4,7};

To pass such an array as an argument to a method, use

twoSum(new int[] {2,4,7},9);

Upvotes: 4

Related Questions