-1
enum Child {
    David(23),
    Johnson(34),
    Brackley(19);
  }

  int age;

  Child(int age) {
    this.age=age; 
  }

  void getAge() {
    return age; 
  }

  public class Test {
    public static void main(String args[]) {
    ---------------------
  }
}

If I had to enter command line arguments, for eg. if I enter java Test David Then it should print "23".

So how can we access enums through command line.. ? what should be written in main method?

Please explain..

tshepang
  • 12,111
  • 21
  • 91
  • 136
Neha Gupta
  • 847
  • 1
  • 8
  • 15

4 Answers4

8

You need to convert the String arg from the command line to an enum value.

Child c = Child.valueOf(args[0]);
duffymo
  • 305,152
  • 44
  • 369
  • 561
5

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.

fge
  • 119,121
  • 33
  • 254
  • 329
1

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

Coder
  • 490
  • 4
  • 18
0

You can do the following

enum Child {
   David(23),
   Johnson(34),
   Brackley(19);

 int age;

 Child(int age) {
   this.age=age; 
 }

 public int getAge() {
   return age; 
 }

   public static void main(String args[]) 
   {
       for(Child c : Child.values())
       {
               //Here you can check for you equality of name taken as command line arg
           System.out.println("Name is " + c + " and age is " + c.getAge());
       }
   }

}

output is as follows

Name is David and age is 23
Name is Johnson and age is 34
Name is Brackley and age is 19
Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289