2010-10-28 5 views
0

Pour mon application de console Java, j'ai besoin d'appeler un ensemble de fonctions avec des arguments donnés par l'utilisateur. Mes opérations O1, O2, .. O5 sont définis comme ENUMTraitement de commande basé sur une console: Chaîne de mappage à énumérer dans Java

enum Operations {O1, O2, O3, O4, O5}; 

Je dois lire args d'entrée utilisateur [0] et appeler la fonction F1, F2, ... F5.

Par exemple l'utilisateur va donner:

>java MyApp O1 5 6 

Pour cela, je suppose que je dois carte piqûre (args [0]) à un ENUM pour que je puisse utiliser sélectionner le commutateur. Comment faire ça?

Répondre

2

Enum.valueOf(Class, String).

Exemple

Operations oper = Enum.valueOf(Operations.class, args[0]); 

jetteront une exception s'il n'y a pas des valeurs ENUM qui correspond args[0]

+0

pourquoi ne pas 'opérations Oper = Operations.valueOf (args [0])' – user102008

0

Je suppose en utilisant ce Chuk plomb de Lee vous pouvez venir avec le programme cool pritty ici ce que je fait.

public class Main { 


public static void main(String[] args) { 

    if(args.length < NUMBER_OF_OPERATORS){ 
     throw new IllegalArgumentException(INSUFFICIENT_OPERANDS); 
    } 

    Operator operator = Enum.valueOf(Operator.class, 
             args[OPERATION_NAME].toUpperCase()); 

    System.out.println(operator.operate(args[FIRST_OPERAND], 
                args[SECOND_OPERAND])); 


} 


private enum Operator { 

    ADD,SUBSTRACT,MULTIPLY,DIVIDE; 

    public String operate(String aString, String bString) { 

     int a = Integer.valueOf(aString); 
     int b = Integer.valueOf(bString); 

     int out = 0; 


     switch(this) { 


      case ADD : out = a + b; break; 
      case SUBSTRACT : out = a - b; break; 
      case MULTIPLY : out = a * b; break; 
      case DIVIDE : out = a/b; break; 
      default: throw new UnsupportedOperationException(); 
     } 

     return String.valueOf(out); 
    } 

} 

private static final int NUMBER_OF_OPERATORS = 3; 
private static final int OPERATION_NAME = 0; 
private static final int FIRST_OPERAND = 1; 
private static final int SECOND_OPERAND = 2; 
private static final String INSUFFICIENT_OPERANDS = 
          "Insufficient operads to carry out the operation."; 

}

Questions connexes