Setting an enum from user input

This question already has an answer here:

  • Lookup Java enum by string value 23 answers

  • Your problem is that you call valueOf(...) but you discard the ContactType object that is returned by this method call.... ie, you never assign the returned object to a variable.

    First get rid of your unnecessary wrapper by changing this:

    public class ContactType
    {
        public enum contactType
        {
            Family,
            Church,
            Friend,
            BusninessColleague,
            ServicePerson,
            Customer,
            Other
        }
    }
    

    to this:

        public enum ContactType
        {
            Family,
            Church,
            Friend,
            BusninessColleague,
            ServicePerson,
            Customer,
            Other
        }
    

    Next use the valueOf to set a ContactType variable.

          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);
    

    Note, I would try to make it more idiot-proof by limiting the selections to a ContactType. For example:

      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/38094.html

    上一篇: 采取字符串并一次比较多个枚举类型

    下一篇: 从用户输入设置枚举