Access enums through command line

This question already has an answer here:

  • Lookup Java enum by string value 23 answers

  • 您需要将String arg从命令行转换为枚举值。

    Child c = Child.valueOf(args[0]);
    

    Use Enum.valueOf() . It takes an enum class and string as as argument and tries and find an enum by that name.

    Note: throws IllegalArgumentException if not found... You'll have to catch it explicitly since this is an unchecked exception.

    Another solution is to use .valueOf() on your enum class itself ( MyEnum.valueOf("whatever") ). Same warning as to exception handling applies.


    Your solution:

    public enum Child {
    
        David(23),
        Johnson(34),
        Brackley(19);
    
        private int age;
    
        private Child(int age) {
            this.age=age; 
        }
    
        int getAge(){
            return age;
        }
    
        public static Child getAgeFromName(String name) {
            for(Child child : Child.values()) {
                if(child.toString().equalsIgnoreCase(name)) {
                    return child;
                }
            }
            return null;
        }
    
        public static void main(String[] args) {
            if(args.length != 0) {
                Child child = Child.getAgeFromName(args[0]);
                if(child != null) {
                    System.out.println(args[0] + " age is " + child.getAge());
                }else {
                    System.out.println("No child exists with name " + args[0]);
                }
            } else {
                System.out.println("please provide a child name");
            }
    
    
        }
    }
    

    INPUT : OUTPUT
    java Child David : David age is 23
    java Child sam : No child exist with name sam
    java Child : Please provide a child name

    Hope this solves your problem

    链接地址: http://www.djcxy.com/p/38088.html

    上一篇: 如何匹配并将字符串切换为枚举?

    下一篇: 通过命令行访问枚举