2

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}};     

}
2
  • There is syntatic sugar at array declaration time, that you can't use any other time. You can do fa1.TT=new int[][]{{1, 2}, {1, 2}, {2, 2}}; Commented Apr 22, 2016 at 13:22
  • you can use any Java Collection to do what you want, but the normal java array won't allow you to do so, Commented Apr 22, 2016 at 13:24

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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;

    }
}

Comments

0

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}};

        }
 }

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.