循环通过枚举

时间:2015-02-13 23:07:03

标签: java enums

我循环查看枚举以找到某个值。如果它找到它继续该程序。否则,它会关闭该计划。我当前的算法是检查所有值是否相等而不是在一个值相等时继续。如果找到一个相等的值,我该如何继续。

    public enum stuff{


    //
    apple("apple.png"),
    banana("banana.png"),
    spinach("spinach.png");

    //


    //Variables
    private String Path;


    //Constructor
    Enemies (String path) {
        Path = path;
    }

    public String getPath() {
        return Path;
    }

}

在另一个班级完成的实际加载

String stuffType = banana;
for (stuff s : stuff.values()) {
            if(stuffType != s.name()){ //checks if any are a banana
                System.exit(0);
            }
        }

1 个答案:

答案 0 :(得分:0)

您可以使用循环,或者您可以使用valueOf方法,该方法已经按名称查找枚举常量,如果没有具有该名称的枚举常量,则抛出IllegalArgumentException。

String stuffType = "banana";

try {
    stuff.valueOf(stuffType);
} catch(IllegalArgumentException e) {

    // stuff doesn't contain an enum constant with a name that matches the value of stuffType
    System.exit(0);
}
相关问题