java - 如何加载方法参数中给定名称的枚举?
问题描述
我正在尝试从方法参数中调用 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 为我工作,但这似乎不是枚举中的有效名称。
解决方案
将 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());
推荐阅读
- solr - 如何在 Solr 4.3 上添加身份验证
- c++ - Qt 应用程序使用来自 Linux 中用户图标主题的图标
- flutter - Admob 未在测试设备上显示生产广告(使用颤振)
- asp.net - C# BasicAuthentication 实现方式
- angular - Angular:在 ngOnInit() 中,当我重新加载组件时,我的 rxjs 函数不运行
- amazon-web-services - 将 ASP.NET Core Web API 发布到 AWS 无服务器 Lambda 时出错:“policyArn”处的“AWSLambdaFullAccess”...成员的长度必须大于
- math - Coq 无法在 `match` 中推断类型参数
- sql - 如何避免配置单元查询中的重复
- r - 在 R 中,如何返回一行中的第 n 个最大数并将结果输出到新列,每行重复?
- python - 从 .txt 文件中读取文本并使用 python 插入字符串