如何将用户在对话框(JOptionPane)中键入的字符串转换为枚举?
我有一个性别枚举。
public enum Gender {
Male("M"), Female("F");
private String value;
Gender(String value){
this.value = value;
}
public String getValue() {
return value;
}
}
此枚举是我课程的构造函数。
This enum is a constructor of my class.
class People {
private String name;
private int id;
private int age;
private Gender x;
}
然后我正在尝试从用户创建此类的新对象,用户输入姓名,身份证,年龄和性别。我正在使用对话框JOptionPane。
我遇到的错误是这一行。
Then I'm trying to create a new object of this class from the user, a user type a name, id, age and gender. I'm using the dialog box JOptionPane. The line I'm getting a error is this one.
public class AppPeople {
public static void main(String[] args) {
Gender gender1; //I tried declaring String gender1
//To get the answer/input below, but didn't work.
gender1 = JOptionPane.showInputDialog(null, "Type Male or Female");
People p1 = new People(name, id, age, Gender1);
}
}
所有其他字段都在对话框中工作,名称,ID和年龄。这个枚举无效。我必须声明id和age字符串才能在对话框上使用它,因此键入的答案进入了字符串变量并将其转换为整数,以匹配类的构造函数。我尝试声明一个新字符串以从对话框中获取输入并将其转换为枚举,但仍然无法正常工作。剩下的唯一字段是将字符串转换为枚举的字段。有人知道我该怎么做才能解决,或者可能有一个新的解决方案。
All the others fields are working from the dialog box, name, id and age. This one that is a enum isn't working. I had to declare id and age string to use it on dialog box, so the answer typed I got into strings variables and converted it to integer, to match the constructor of the class. I tried declaring a new string to get the input from dialog box and convert it to enum but still didn't work. The only field left is this one to convert a string to enum. Does anyone know what can I do to fix or maybe a new solution.
您可以使用
gender1 = Gender.valueOf(JOptionPane.showInputDialog(null, "Type Male or Female").toUpperCase());