0

Normally, to define an array in Processing, I would do something like this:

int[] array = {1, 3, 5};

However, doing that within a function makes it a local variable, so I did this initially:

String[] array;
void setup() {
  array = {"String"};
}

But it gives me this Syntax Error:

Syntax Error - Incomplete statement or extra code near ‘extraneous input '{' expecting {'color', HexColorLiteral, CHAR_LITERAL, 'boolean', 'byte', 'char', 'double', 'float', 'int', 'long', 'new', 'short', 'super', 'this', 'var', 'void', DECIMAL_LITERAL, HEX_LITERAL, OCT_LITERAL, BINARY_LITERAL, FLOAT_LITERAL, HEX_FLOAT_LITERAL, BOOL_LITERAL, STRING_LITERAL, MULTI_STRING_LIT, 'null', '(', '<', '!', '~', '++', '--', '+', '-', '@', IDENTIFIER}’?

This should be a relatively simple problem to solve though, I'm just missing something really big.

If you're wondering why I need to define it inside a function, it's because I need it for an array that contains a loadImage(), which needs to be called inside of or after void setup(), which runs once, and once only.

I tried declaring the variable like this: Array array; Didn't work, gave me the same error.

For some reason, 2-D arrays, or arrays containing arrays gave me a different error.

int[][] array; 
void setup() {  
  array = {{1, 3, 5}};
}

The error was this: Syntax Error - Missing operator, semicolon, or ‘}’ near ‘{’?

Edit: I am aware that you can do it like this:

int[] array = new int[3];
void setup() {
    array[0] = 1;
    array[1] = 3;
    array[2] = 5;
}

But I am unaware of how to do it with 2-D arrays.

  • 1
    Which java version are you using? Please have a look at this answer https://stackoverflow.com/questions/1154008/any-way-to-declare-an-array-in-line – Tej Feb 07 '23 at 01:34
  • 1
    check this https://stackoverflow.com/questions/3160347/java-how-initialize-an-array-in-java-in-one-line – Chandika Feb 07 '23 at 01:36
  • *I'm just missing something really big.* The sequence `{1,3,5}` is an [initializer](https://docs.oracle.com/javase/specs/jls/se11/html/jls-10.html#jls-10.6), not an expression, and therefore can only occur in a declaration, not an assignment. – undefined symbol Feb 07 '23 at 02:26

1 Answers1

2

You need to use the new keyword to initialize an array (except if it's inline with the declaration):

array = new int[][] {{1, 3, 5}};
shmosel
  • 49,289
  • 6
  • 73
  • 138