2016-04-22 27 views
2

我想做DFA類的多個對象並通過對象初始化它的字段值。我不想初始化數組大小。如何使用{}直接通過對象初始化數組字段。如何通過對象初始化數組?

當我在類初始化它的工作正常。

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

但是當我嘗試像那樣通過對象初始化那麼它不工作。 在這裏我的代碼。

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

} 
+0

有一個在數組聲明時語法糖,你不能使用任何其它時間。你可以做'fa1.TT = new int [] [] {{1,2},{1,2},{2,2}};' –

+0

你可以使用任何Java集合來做你想做的事情,但是正常的java數組不會讓你這樣做, – xelilof

回答

2

你可以做

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

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

我建議使用小寫字段名稱要麼。

0

數組常量只能在初始化

被用來讓你無論是把它直接在變量(int[] FS = { 1 };),或者你首先初始化數組做到這一點。

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; 

    } 
} 
0

以下語法:

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

Array Initializer語法。你可以在聲明數組時使用它。你不能分開數組聲明和初始化語法。

您應該改用fa1.FS = new int[]{1};

0

在這裏你去:

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

     } 
}