首页 > 解决方案 > 如何加载方法参数中给定名称的枚举?

问题描述

我正在尝试从方法参数中调用 Enum 的值。

试过代码,如果里面有很多无用或虚假的东西,对不起。显然这不会执行!这只是我认为相关的部分

public int choosemachines(int cost){    

  Scanner scanner = new Scanner(System.in);
  System.out.println("Which One Would You Like?");

  int choice = scanner.nextInt(); 
  switch (choice) {         
      case 1:
        writeArrays("MACHINE1", 1);
        break;
}

public void writeArrays(String **machine**, int arrint) {   

        if (cost >= machines.**machine**.getcost()) {

            int alsize = twoDim.size();
            twoDim.add(new ArrayList<Integer>());
            twoDim.get(alsize).add(arrint);
            twoDim.get(alsize).add(1);
            twoDim.get(alsize).add(1);
            System.out.println(alsize);

             for (ArrayList<Integer> row : twoDim)
             {
                for (Integer element : row)
                {
                   System.out.print(element + "        ");
                }
                System.out.println();
            }
        }
            else {
            System.out.println("Can't Afford It...");

            }   
        }

public enum machines {

    MACHINE1("General Electric Caffeinator", 1500, "TWO"),
    MACHINE2("Sleepless Night", 2000, "ONE")
    ;

    private String name;
    private int cost;
    private String coffeeType;

    machines (String n, int c, String cT) {
        name = n;
        cost = c;
        coffeeType = cT;
    }

    String getname(){
        return name;
    }

    int getcost(){
        return cost;
    }

    String getcoffeeType() {
        return coffeeType;
    }
}

我希望 if 函数能够将成本列在枚举的第二位。也可以使用整数而不是 MACHINE1 为我工作,但这似乎不是枚举中的有效名称。

标签: javamethodsenumsarguments

解决方案


将 Enum 重命名Machine为按照 java 命名约定,您可以这样做:

public void writeArrays(String machineName, int arrint) {

    int cost = 0;
    for(Machine machine : Machine.values()){
        if(machine.getname().equals(machineName)){
            cost = machine.getcost();
            break;
        }
    }
    //todo add rest of the code 
}

您还可以添加一个实用程序方法Machines

 public static Machine getByName(String machineName) {

    for(Machine machine : Machine.values()){
        if(machine.getname().equals(machineName))
            return machine;
    }
    return null;
}

使用以下方法进行测试:System.out.println(Machine.getByName("Sleepless Night").getcost());


推荐阅读