2017-02-12 56 views
-1

我不知道如何添加到數組枚舉。我使用enum和它的作品使用了字段的構造函數,但是我不知道如何在沒有字段的構造函數中使用它。我希望你明白我在想什麼。在我的代碼中,我評論我認爲我有問題的地方。 我有:我如何使構造函數沒有帶枚舉的字段?

public enum Components { 
    WIFI, BLUETOOTH, CAMERA, SSD 
} 

public Laptop(){ 
    System.out.println("name of producer:"); 
    String producername = Main.sc.nextLine(); 
    System.out.println("name of model:"); 
    String modelname = Main.sc.nextLine(); 
    System.out.println("ram:"); 
    int ram = Main.sc.nextInt(); 
    System.out.println("cpu:"); 
    String cpu = Main.sc.nextLine(); 
    cpu = Main.sc.nextLine(); 
    System.out.println("components:"); 
    System.out.println("how many components do you want to add?"); 
    int z = Main.sc.nextInt(); 
    Components[] com = new Components[z]; 
    for(int i=0; i<com.length;i++){ 
     com[i] = //<-- how to add enum in array? 
    } 

    setProducerName(producername); 
    setModelName(modelname); 
    setRam(ram); 
    setCpu(cpu); 
    setComponents(com); 
} 

我的構造函數使用字段是這樣的,它的工作原理。

public Laptop(String ProducerName, String ModelName, int Ram, String Cpu, Components... components) { 
    super(); 
    this.ProducerName= ProducerName; 
    this.ModelName= ModelName; 
    this.Ram= Ram; 
    this.Cpu= Cpu; 
    this.components= new Components[components.length]; 
    this.components= Arrays.copyOf(components, components.length); 
} 

請幫忙。

回答

0

我不是100%清楚你在問什麼,但是你可以從枚舉本身得到一個用enum常量填充的數組:Components.values()將返回一個數組全部 enum常量。這將從根本上恢復:

new Components[]{Components.WIFI, Components.BLUETOOTH, 
    Components.CAMERA, Components.SSD} 

方的建議:不要用你的筆記本電腦的構造函數內掃描儀,而事實上,讓所有的用戶界面代碼的所有構造函數和該類的實例方法。所有的用戶界面代碼都屬於別處

1

您可以通過名稱獲取enum值。

public enum Components { 
    WIFI, BLUETOOTH, CAMERA, SSD 
} 

public Laptop(){ 
    ... 
    Components[] com = new Components[z]; 
    for(int i=0; i<com.length;i++){ 
     com[i] = Components.valueOf(Main.sc.nextLine()); 
    } 
    ... 
} 
相關問題