2013-11-05 14 views
0

我在另一個類中設置了String數組,但是當我嘗試以某種方式設置該值時返回「數組常量只能用於初始值設定項」。爲什麼「數組常量只能在初始值設定項中使用」當數組被定義爲創建它的類之外時

import java.util.Scanner; 

class People { 

    String[] names; 
    int age; 
    int height; 

} 

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

     People person1 = new People(); 

     People person2 = new People(); 

     People person3 = new People(); 

     // I can set the values like this. 

     person1.names[0] = "Joe"; 
     person1.names[2] = "!"; 
     person1.names[3] = "?"; 

     // But not like the more effective way. 
     person2.names = {"Apple", "Banana"}; 

     person1.age = 13; 
     person1.height = 164; 

    } 
} 
+0

缺少'新的String []' –

回答

2

以下語法用於在除聲明行以外的線實例的數組:

person2.names = new String[] {"Apple", "Banana"}; 
相關問題