0

I am trying to create a two dimensional array put it keeps giving me errors.~ Could you help figure out what I am doing wrong?

char [][] numero0 = new char [7][4];
numero0[][] = { {'.', '#', '#', '.'},
                {'#', '.', '.', '#'},
                {'#', '.', '.', '#'},
                {'.', '.', '.', '.'},
                {'#', '.', '.', '#'},
                {'#', '.', '.', '#'},
                {'.', '#', '#', '.'} };

Erros:

illegal start of expression
not a statement
';' expected

  • In the second line, you use the array initialization syntax, that is only valid when declaring an array. But you assigning to an array. – Johannes Kuhn Feb 17 '18 at 14:26

3 Answers3

1

You can't use initializer syntax, except when declaring the array variable.

So, either:

char[][] array = { { ... } };

or

char[][] array = new char[][] { { ... } };

or

char[][] array;  // Don't assign new char[7][4] here, it is overwritten in the next line.
array = new char[][] { { ... } };
Andy Turner
  • 122,430
  • 10
  • 138
  • 216
0

numero0[][] = { { ... }}; should be numero0 = new char[][] { { ... } };.

Please see the following snippet.

lexicore
  • 39,549
  • 12
  • 108
  • 193
0

Example Code :

public class TwoDarray {
    public static void main(String args[]){


        char numero0[][] = { {'.', '#', '#', '.'},
                        {'#', '.', '.', '#'},
                        {'#', '.', '.', '#'},
                        {'.', '.', '.', '.'},
                        {'#', '.', '.', '#'},
                        {'#', '.', '.', '#'},
                        {'.', '#', '#', '.'} };


        for (int i = 0; i < numero0.length; i++) { //printing 2d-array as matrix with index so that you get a better picture of 2d array.
            for (int j = 0; j < numero0[i].length; j++) {
                System.out.print(" ( " + i + "," + j + " ) " + numero0[i][j]);
            }
            System.out.println();
        }
    }


}

printing 2d-array as matrix with index so that you get a better picture of 2d array.

Output :

enter image description here

Correct way To declare and Initialize two dimensional Array in Java :

Syntax to Declare Multidimensional Array in java :

dataType[][] arrayRefVar; (or)  
dataType [][]arrayRefVar; (or)  
dataType arrayRefVar[][]; (or)  
dataType []arrayRefVar[];  

Example to instantiate Multidimensional Array in java :

int[][] arr=new int[3][3];//3 row and 3 column  

Example to initialize Multidimensional Array in java :

arr[0][0]=1;  
arr[0][1]=2;  
arr[0][2]=3;  
arr[1][0]=4;  
arr[1][1]=5;  
arr[1][2]=6;  
arr[2][0]=7;  
arr[2][1]=8;  
arr[2][2]=9; 

Declaring and initializing 2D array :

int arr[][]={{1,2,3},{4,5,6},{7,8,9}};  

NOTE:

You were Instantiating on line 1 i.e char [][] numero0 = new char [7][4]; and Trying to initialize array without providing index on second line.

You can use loop to initialize and print multidimensional array.

I hope I was helpful :)

Abhi
  • 245
  • 1
  • 8