Muhammad Sajjad
Muhammad Sajjad

Reputation: 73

How to Initialize array through object?

I want to make multiple object of DFA class and Initialize its field value by object through . I don't want to initialize array size. How I Initialize array field direct through object using {}.

when I Initialize like that in class its work fine.

  int[][] TT={{1,2},{2,1}};

but when I try to initilize like that through object then its not work. Here my code.

public class DFA {

   int[][] TT;
   int IS;
   int[] FS;
 }
 public static void main(String[] args) {

    DFA fa1=new DFA();
    fa1.IS=0;
    fa1.FS={1};                        //Both FS and TT give error 
    fa1.TT={{1, 2}, {1, 2}, {2, 2}};     

}

Upvotes: 2

Views: 109

Answers (4)

justAbit
justAbit

Reputation: 4256

Below syntax:

int[][] TT={{1,2},{2,1}};

is Array Initializer syntax. You can use it when you are declaring array. You can not separate array declaration and initializer syntax.

You should use fa1.FS = new int[]{1}; instead.

Upvotes: 0

Adnan Isajbegovic
Adnan Isajbegovic

Reputation: 2307

Here you go:

    public class DFA {

        int[][] TT;
        int IS;
        int[] FS;

        public static void main(String[] args) {

            DFA fa1=new DFA();
            fa1.IS=0;
            fa1.FS=new int[]{1};                        //Both FS and TT give error
            fa1.TT= new int[][]{{1, 2}, {1, 2}, {2, 2}};

        }
 }

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533880

You can do either

int[][] tt = {{1, 2}, {1, 2}, {2, 2}};
fa.TT = tt;

or

fa1.TT = new int[][] {{1, 2}, {1, 2}, {2, 2}};

I suggest using lowerCase for field names.

Upvotes: 2

PendingValue
PendingValue

Reputation: 250

Array constants can only be used in initializers

So you either put it directly at the variables (int[] FS = { 1 };), or you do it with initializing the array first.

public class DFA {

    int[][] TT;
    int IS;
    int[] FS = { 1 };

    public static void main(String[] args) {

        DFA fa1 = new DFA();
        fa1.IS = 0;
        int[] tmpFS = { 1 };
        fa1.FS = tmpFS;
        int[][] tmpTT = { { 1, 2 }, { 1, 2 }, { 2, 2 } };
        fa1.TT = tmpTT;

    }
}

Upvotes: 0

Related Questions