Bowen_Yang
Bowen_Yang

Reputation: 1

Syntax error on token ";"

I'm trying to create a two dimensional array in a class where there is no main method. I could successfully initialize the array with the code:

double[][] nameArray = new double[m][n];  //m、n is the size

but when I try to assign a value to the array

nameArray[0][0] = 0;

a error comes up and shows the ";" is wrong in the syntax

double[][] nameArray = new double[m][n];

however, this code works in my main method. I got confused and want to know what went wrong?

can anyone answer my question? really appreciate it.

Upvotes: 0

Views: 804

Answers (3)

Azar
Azar

Reputation: 1106

That is simply illegal syntax. You can initialize your array outside of a method, but you cannot put other statements outside of a method, such as setting a specific value in the array. Consider adding that statement to your constructor instead.

Upvotes: 6

Bob Kuhar
Bob Kuhar

Reputation: 11120

Are you asking how to initialize a 2D array in Java?

import java.util.*;

public class ArrayInit {
    public int[][] oneArray = { { 0, 0 }, { 0, 1 }, { 1, 0 }, { 1, 1 } };
    public int[][] twoArray = new int[4][2];
    public int[][] threeArray = new int[4][2];
    {
        // you don't usually see it done this way.
        threeArray[0][0] = 0;
        threeArray[0][1] = 0;
        threeArray[1][0] = 0;
        threeArray[1][1] = 1;
        threeArray[2][0] = 1;
        threeArray[2][1] = 0;
        threeArray[3][0] = 1;
        threeArray[3][1] = 1;
    }

    public ArrayInit() {
        // This looks cumbersome too
        twoArray[0][0] = 0;
        twoArray[0][1] = 0;
        twoArray[1][0] = 0;
        twoArray[1][1] = 1;
        twoArray[2][0] = 1;
        twoArray[2][1] = 0;
        twoArray[3][0] = 1;
        twoArray[3][1] = 1;
    }

    public static void main( String[] args ) {
        ArrayInit ai = new ArrayInit();
        System.out.println( Arrays.deepToString( ai.oneArray ) );
        System.out.println( Arrays.deepToString( ai.twoArray ) );
        System.out.println( Arrays.deepToString( ai.threeArray ) );
    }
}

You can, at the time of declaration, fully initialize the array like "oneArray" above. Alternatively, you can, at the time of declaration, give the array a specific size like "twoArray" above. You cannot, at the time of declaration, give the array a specific size and initialize some portion of it.

Upvotes: 0

Inanepenguin
Inanepenguin

Reputation: 178

You may initialize the array in your class, and you may even initialize with initial values, but you cannot execute code that will assign values once the variable is created. There are languages where this would be possible, but Java is not one of them.

Upvotes: 0

Related Questions