遍历枚举
Looping through enum
我正在遍历枚举以查找特定值。如果找到它,它将继续执行该程序。否则,它会关闭程序。我当前的算法正在检查是否所有值都相等,而不是在一个值相等时继续。如果找到一个相等的值,如何让它继续。
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;
}
}
实际加载在另一个 class
String stuffType = banana;
for (stuff s : stuff.values()) {
if(stuffType != s.name()){ //checks if any are a banana
System.exit(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);
}
我正在遍历枚举以查找特定值。如果找到它,它将继续执行该程序。否则,它会关闭程序。我当前的算法正在检查是否所有值都相等,而不是在一个值相等时继续。如果找到一个相等的值,如何让它继续。
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;
}
}
实际加载在另一个 class
String stuffType = banana;
for (stuff s : stuff.values()) {
if(stuffType != s.name()){ //checks if any are a banana
System.exit(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);
}