2017-02-12 82 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()); 
    } 
    ... 
}