从用户输入设置枚举
这个问题在这里已经有了答案:
你的问题是你调用valueOf(...)
但是你放弃了这个方法调用返回的ContactType对象....也就是说,你永远不会把返回的对象赋值给一个变量。
首先通过改变这个来摆脱你不必要的包装:
public class ContactType
{
public enum contactType
{
Family,
Church,
Friend,
BusninessColleague,
ServicePerson,
Customer,
Other
}
}
对此:
public enum ContactType
{
Family,
Church,
Friend,
BusninessColleague,
ServicePerson,
Customer,
Other
}
接下来使用valueOf设置ContactType变量。
strContactType = JOptionPane.showInputDialog ("Please enter contact type (Family, Church, BusinessColleague, ServicePerson, Customer, or Other)");
ContactType contactType = ContactType.valueOf(strContactType);
JOptionPane.showMessageDialog (null, strContactType);
c1.setContactType (contactType);
请注意,我会尝试通过将选择限制为ContactType来使其更加白痴。 例如:
Object selection = JOptionPane.showInputDialog(null,
"Choose a contact type", "Contact Type",
JOptionPane.INFORMATION_MESSAGE, null,
ContactType.values(), ContactType.values()[0]);
// check that selection is not null before using
System.out.println(selection);
调用ContactType.valueOf(strContactType)将字符串名称转换为枚举值
链接地址: http://www.djcxy.com/p/38093.html上一篇: Setting an enum from user input
下一篇: Get Enum instance