Setting an enum from user input
本问题已经有最佳答案,请猛点这里访问。
选择Java备份并尝试熟悉EnUM类型。我正在尝试创建一个通讯簿,用户可以在其中创建联系人。我已经创建了所有的东西,但我挂断了设置一个联系类型(家庭,朋友,业务等…)我在一个单独的Java类中设置了一个EnUM类。
1 2 3 4 5 6 7 8 9 10 11 12 13 | public class ContactType { public enum contactType { Family, Church, Friend, BusninessColleague, ServicePerson, Customer, Other } } |
我的联系人类看起来像:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | public class Contacts { private contactType contact; private String name; private String streetAddress; private String city; private String state; private String zipCode; private String phone; private String email; private String photo; public Contacts ( ) { contact = null; name ="XXX XXX"; streetAddress ="XXX"; state ="XX"; zipCode ="00000"; phone ="XXX-XXXX"; email ="[email protected]"; photo ="XXX.jpg"; } public Contacts (ContactType contactType, String name, String streetAddress, String city, String state, String zipCode, String phone, String email, String photo) { this.contact = contactType; this.name = name; this.streetAddress = streetAddress; this.city = city; this.state = state; this.zipCode = zipCode; this.phone = phone; this.email = email; this.photo = photo; } public ContactType getContactType ( ) { return contact; } public void setContactType (ContactType input) { this.contact = input; } //rest of code |
最后是我的驱动程序,它包括一个菜单(除了设置联系人类型之外,其他所有功能都可以工作,所以为了保持简短,我刚刚包含了这段代码片段):
1 2 3 4 5 6 7 8 9 10 11 | switch (iSelection) { case 1: c1 = new Contacts(); //creates a new contact break; case 2: strContactType = JOptionPane.showInputDialog ("Please enter contact type (Family, Church, BusinessColleague, ServicePerson, Customer, or Other)"); contactType.valueOf(strContactType); JOptionPane.showMessageDialog (null, strContactType); c1.setContactType (strContactType); break; |
我知道我在
您的问题是,您调用
首先,通过更改以下内容来除去不必要的包装:
1 2 3 4 5 6 7 8 9 10 11 12 13 | public class ContactType { public enum contactType { Family, Church, Friend, BusninessColleague, ServicePerson, Customer, Other } } |
对此:
1 2 3 4 5 6 7 8 9 10 | public enum ContactType { Family, Church, Friend, BusninessColleague, ServicePerson, Customer, Other } |
接下来,使用valueof设置contacttype变量。
1 2 3 4 | 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); |
注意,我会尝试通过将选择限制到一个联系人类型来使其更为白痴。例如:
1 2 3 4 5 6 7 | 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)将字符串名称转换为枚举值