9 Replies Latest reply: Jun 18, 2008 12:51 PM by 807591 RSS

    Help with Switch statements using Enums?

    807591
      Hello, i need help with writing switch statements involving enums. Researched a lot but still cant find desired answer so going to ask here. Ok i'll cut story short.

      Im writing a calculator program. The main problem is writing code for controlling the engine of calculator which sequences of sum actions.

      I have enum class on itself. Atm i think thats ok. I have another class - the engine which does the work.

      I planned to have a switch statement which takes in parameter of a string n. This string n is received from the user interface when users press a button say; "1 + 2 = " which each time n should be "1", "+", "2" and "=" respectively.
      My algorithm would be as follows checking if its a operator(+) a case carry out adding etc.. each case producing its own task. ( I know i can do it with many simple if..else but that is bad programming technique hence im not going down that route) So here the problem arises - i cant get the switch to successfully complete its task... How about look at my code to understand it better.

      I have posted below all the relevant code i got so far, not including the swing codes because they are not needed here...
      ...
      ValidOperators v;
      
      public Calculator_Engine(ValidOperators v){
                stack = new Stack(20);
                //The creation of the stack...
                this.v = v;          
           }
      
      public void main_Engine(String n){
             ValidOperators v = ValidOperators.numbers;
                      *vo = vo.valueOf(n);*
      
           switch(v){
           case Add: add();  break;
           case Sub: sub(); break;
           case Mul: Mul(); break;
           case Div: Div(); break;
           case Eq:sum = stack.sPop(); System.out.println("Sum= " + sum);
           default: double number = Integer.parseInt(n);
                         numberPressed(number);
                         break;
                        //default meaning its number so pass it to a method to do a job
                }
                }
      public enum ValidOperators {
           
           Add("+"), Sub("-"), Mul("X"), Div("/"), 
           Eq("="), Numbers("?"); }
           
      Notes*
      It gives out error: "No enum const class ValidOperators.+" when i press button +.
      It has nothing to do with listeners as it highlighted the error is coming from the line:switch(v){
      I think i know where the problem is.. the line "vo = vo.valueOf(n);"

      This line gets the string and store the enum as that value instead of Add, Sub etc... So how would i solve the problem?
      But.. I dont know how to fix it. ANy help would be good
      Need more info please ask!

      Thanks in advance.
        • 1. Re: Help with Switch statements using Enums?
          807591
          [http://forum.java.sun.com/thread.jspa?threadID=5156033]
          • 2. Re: Help with Switch statements using Enums?
            807591
            There's more code to ValidOperators, right, like a constructor to handle the strings "-"? The automatically provided static method valueOf maps "Add" etc... to ValidOperators objects, not "-". You will have to write you own mapping method for those symbol strings.
            • 3. Re: Help with Switch statements using Enums?
              807591
              My problem is different here.

              Im not exactly taken in.. for e.g. "ValidOperators.Add" to the varaible v

              BUT im taken in string of the enum..

              So how can i connect that together to make it know when it sees string "+", it is enum ValidOperators.Add??
              • 4. Re: Help with Switch statements using Enums?
                807591
                Theresonly1 wrote:
                My problem is different here.

                Im not exactly taken in.. for e.g. "ValidOperators.Add" to the varaible v

                BUT im taken in string of the enum..

                So how can i connect that together to make it know when it sees string "+", it is enum ValidOperators.Add??
                You need to write that code yourself, Maybe use a Map<String, ValidOperator>?
                • 5. Re: Help with Switch statements using Enums?
                  807591
                  Right, what youve suggested there is really good, whilst just thought about it. Im going to try your suggestion out tomorrow as it is very late in my country. Once i feel thats what im looking for im going to award you duke stars for your effort.

                  Thanks for your reply and contribution.

                  All the best.

                  And i'll probably need to disturb with more questions if i get stuck again...
                  • 6. Re: Help with Switch statements using Enums?
                    807591
                    By the way, did you digest the Operation example on this page: [http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html]

                    It is an example of defining a polymorphic method for enums. Hmmm...
                    • 7. Re: Help with Switch statements using Enums?
                      807591
                      DrLaszloJamf wrote:
                      By the way, did you digest the Operation example on this page: [http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html]

                      It is an example of defining a polymorphic method for enums. Hmmm...
                      Right i just read over the page u suggested. I find it quite useful possibly not that great as i expected.

                      Regarding the post you posted earlier

                      "There's more code to ValidOperators, right, like a constructor to handle the strings "-"? The automatically provided static method valueOf maps "Add" etc... to ValidOperators objects, not "-". You will have to write you own mapping method for those symbol strings. "

                      What do you exactly mean?
                      • 8. Re: Help with Switch statements using Enums?
                        807591
                        demo:
                        import java.util.*;
                        
                        public class EnumExample {
                            enum E {
                                STAR("*"), HASH("#");
                        
                                private String symbol;
                        
                                private static Map<String, E> map = new HashMap<String, E>();
                                static {
                                    put(STAR);
                                    put(HASH);
                                }
                        
                                public String getSymbol() {
                                    return symbol;
                                }
                        
                                private E(String symbol) {
                                    this.symbol = symbol;
                                }
                        
                                private static void put(E e) {
                                    map.put(e.getSymbol(), e);
                                }
                        
                                public static E parse(String symbol) {
                                    return map.get(symbol);
                                }
                            }
                        
                            public static void main(String[] args) {
                                System.out.println(E.valueOf("STAR")); //succeeds
                                System.out.println(E.parse("*")); //succeeds
                        
                                System.out.println(E.parse("STAR")); //fails: null
                                System.out.println(E.valueOf("*")); //fails: IllegalArgumentException
                            }
                        }
                        • 9. Re: Help with Switch statements using Enums?
                          807591
                          Thanks very much.

                          You have answered my question really effectively!

                          Cheers! take care...