1

I have no problem calling methods that require String or int inputs. For example:

return stringMethod("Hello World");
return intMethod(1,2,3);

but I'm having an issue with the syntax when calling a method which requires array of ints for the input. The syntax I use to call the method countEvens in the code below is not working.

public class _01_countEvens{
    public static void main(String[] args){
        return countEvens({2,4,6,7});
        }

    }
    public int countEvens(int[] nums){
        int result = 0;

        for(int x = 0; x < nums.length; x++){
            if(nums[x] % 2 == 0) result++;
        }
        return result;
    }
}

enter image description here

dbconfession
  • 1,147
  • 2
  • 23
  • 36
  • 2
    In addition to the answers below, you can't return an `int` from `main()`, because it is declared as a `void` method. – jonhopkins Feb 01 '14 at 00:45
  • I'm actually using Arrays.toString() to output, i was just trying to simplify. But thanks, you're right. – dbconfession Feb 01 '14 at 03:07

3 Answers3

8

This syntax

{2,4,6,7}

is the array creation syntax and can only be used in array creation expressions

new int[]{2,4,6,7}

Read the official Java tutorial on Arrays here.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • thanks. I added an image to my original post of the actual problem I'm working on at codingbat.com The method public int countEvens(int[] nums) works and the tests he runs are in the format countEvens({2, 1, 2, 3, 4}) is being used to call it. This is why I'm lost. When I call it that way in a Eclipse or Netbeans, it doesn't work. – dbconfession Feb 01 '14 at 03:14
  • @StuartKuredjian That's just notation for the website, it's invalid Java syntax. – Sotirios Delimanolis Feb 01 '14 at 03:16
  • @StuartKuredjian See [here](http://stackoverflow.com/questions/13665930/use-of-ellipsis-in-java) about the ellipsis. – Sotirios Delimanolis Feb 01 '14 at 03:44
6

Either change your method header to:

public int countEvents(int... nums)

And remove the { and } in the call to countEvents,

Or pass: new int[]{2, 4, 6, 7} as an argument.

Sibbo
  • 3,796
  • 2
  • 23
  • 41
Josh M
  • 11,611
  • 7
  • 39
  • 49
  • I tried using int... instead of int[] and it doesn't work. But doesn't it need to be [] to specify it as an array? And what does ... mean? – dbconfession Feb 01 '14 at 03:10
  • ok calling it with countEvens(new int[]{2, 4, 6, 7}); worked. Thanks. Though I'd still like to know who to make your first suggestion work. Not sure what int... means. – dbconfession Feb 01 '14 at 03:27
  • @StuartKuredjian Rather than trying to explain it myself, a good explanation can be found [here](http://stackoverflow.com/a/2367412/1255746). – Josh M Feb 01 '14 at 04:27
0

Array:

int[] a = {0,1,2,3,4,5};

Double Array:

int[][] a2 = {
        {0,1,2}
        {3,4,5}
};

From there on, just add arrays inside each array. You shouldn't have to make that many dimensions though.