Use Enum to Switch on Strings where one string is a java reserved word.

Hi,
I'm having problems switching on a string using enums, when one of the strings is a java reserved word. Any suggestions would be appreciated. Or maybe even a suggestion that I should just be stringing together if-else if and doing string compares rather than a switch.
I've been using the following method to switch on strings.
public enum MyEnum
foo, bar, novalue;
public static MyEnum stringValue(String string)
try { return valueOf(string); }
catch (Exception e) { return novalue; }
Then I can switch like
switch(MyEnum.stringValue( someString )
case foo:
break;
case bar:
break;
default:
break;
Now I have run into the problem where one of the strings I need to use is "int", which is a reserved word in java, so I have to modify.
What is the best way to handle this?
I could just not add it to the Enum and handle it at the switch like this...
switch(MyEnum.stringValue( someString )
case foo:
break;
case bar:
break;
default:
if(someString.equals("int") {  ... }
break;
OR...
I could change the Enum, and return intx, by checking if the string is "int". I could check before the valueOf, or during the exception, but I know it's not good practice to use Exceptions in the normal execution of your code... as it's not really an exception.
public enum MyEnum
foo, bar, intx, novalue;
public static MyEnum stringValue(String string)
if(string.equals("int") { return intx; }
try { return valueOf(string); }
catch (Exception e) { return novalue; }
OR...
public enum MyEnum
foo, bar, intx, novalue;
public static MyEnum stringValue(String string)
try { return valueOf(string); }
catch (Exception e) {
if(string.equals("int") { return intx; }
else return novalue;
}

My advice is still to not name the enum the same as the value of the string you want to test for. That page I linked to shows how to have enums with parameters. Then you could have an enum whose name is (say) JavaInt and whose string value is "int".
But frankly if I wanted to map Strings to actions I would just use a Map<String, Action> instead of trying to force my code into an antique construction like switch.

Similar Messages

  • How to Exclude Java Reserved Words Using StringTokenizer

    Hi, i'm trying to exclude identifiers and java reserved words using StringTokenizer from an input file outputting the remaining words alphabetically ordered with the line, on witch they occur, in front of the word.
    So far my code does all that, except exclude those words. I'm kind on a dead end... Any suggestions?
    The code:
    public class Interpreter{
        /* Uses a Binary Search Tree      */
        public static void main(String args[ ]) {
            String path = null;
            for (int j = 0; j < args.length; j++) {
                try {
                    // Step 1, read the input file
                    path   = args[j];
                    FileReader input = new FileReader(args[j]);
                    BufferedReader br = new BufferedReader(input);
                    String line;
                    int count = 1;
                    String word;
                    // Step 2, create an empty Tree
                    BST tree = new BST();
                    while((line = br.readLine())!=null){
                        StringTokenizer str = new StringTokenizer(line);
                        while (str.hasMoreTokens()){
                            word = str.nextToken();
                            tree.insert(word,count);
                        count++;
                    // We're done, print out contents of Tree!
                    tree.print();
                    // Error Handling
                    //check for IO problem with bad file
                } catch (IOException e) {
                    System.out.println("There was a problem with the filename you entered.");
                    //check for no filename entered at command prompt
                } catch (ArrayIndexOutOfBoundsException e) {
                    System.out.println("Please include a filename when running this program.");
    }Edited by: Redol on Dec 12, 2007 8:32 PM
    Edited by: Redol on Dec 12, 2007 8:33 PM

    use split instead of tokenizer.
    public String[] splitString( String line, String delim )
        String[] tokens = null;
        if( line != null )
            tokens = line.split( delim );
        return tokens;
    }

  • Where can find out the java key word elucidation

    Where can find out the java key word elucidation?
    thx

    here:
    http://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html
    then here:
    http://java.sun.com/docs/books/jls/second_edition/html/jIX.fm.html

  • Enum or EnumMap to store String constants using enums?

    I have decided to use enums to store some String
    constants. What are the pros and cons of using a
    simple enum versus using EnumMap? What are
    the differences?
    If going with the simple enum option, I would just
    do as in the following example:
    // The typesafe enum pattern
    public class Suit {
        private final String name;
        private Suit(String name) { this.name = name; }
        public String toString()  { return name; }
        public static final Suit CLUBS =
            new Suit("clubs");
        public static final Suit DIAMONDS =
            new Suit("diamonds");
        public static final Suit HEARTS =
            new Suit("hearts");
        public static final Suit SPADES =
            new Suit("spades");
    }A System.out.println(CLUBS); prints out "clubs".
    Or is EnumMap a better choice? If so, why? If not,
    then why?

    jverd wrote:
    sunfun99 wrote:
    +3.1459378192030194732612839423...+ is a constant, but not a named constant. If I give the constant a name, like "PI", then I can use that name to access the constant (instead of having to repeat the long constant literal every time I want to use it). Now, I want to use a number of constants across various classes, so I give each of these constants a name. What I then have is a number of named constants. To name a constant means that I map a name to a value:That's not what "mapping" means in this context. Really? Even the Collections tutorial says it, "Map � an object that maps keys to values". And - not surprising - the classes/interfaces "Map", "Set", etc. are named so because they mimic these mathematical concepts.
    It appears you don't know what java.util.Map is for. java.util.Map is "an object that maps keys to values". It's an interface that also provides various methods that allows for various dealings with the data, such as removing or adding mappings, provide the value given the name, give the total number of mappings, etc.
    Then define an enum.As I said earlier, I believe you, and that's what I will do.
    What makes you think that EnumMap is a "more advanced implementation" of enums? (It's not. It's not an implementation of enums at all.) What does "more advanced" even mean here?Sorry, my mistake. It's not an implementation of enums. However, it takes enums as parameters. In that sense, using EnumMap would indirectly imply a more complicated way of using enums, since not only do I create enums, but then I have to put the into EnumMap.

  • Enum vs static final String

    I was going to use static final Strings as enumerated constants in my application, but would like to see if I should be using enums instead.
    In terms of efficiency, if I have, say, 5 enumerated elements, will only one copy of the enumerated element be in memory, like a static final String? So regardless of how many times I refer to it, all references point to the same instance (I'm not sure if what I just said even makes sense in the context of enums, but perhaps you could clarify).
    Are there any reasons why for enumerated constants that are known at development time, why static final Strings (or static final anything, for that matter) should be used instead of enums if you're using JDK 1.5?
    Thanks.

    In terms of efficiency, if I have, say, 5 enumerated elements, will only one copy of
    the enumerated element be in memory, like a static final String?I don't know if it addesses your concerns, but the the Java Language Specification says this about enums: "It is a compile-time error to attempt to explicitly instantiate an enum type (�15.9.1). The final clone method in Enum ensures that enum constants can never be cloned, and the special treatment by the serialization mechanism ensures that duplicate instances are never created as a result of deserialization. Reflective instantiation of enum types is prohibited. Together, these four things ensure that no instances of an enum type exist beyond those defined by the enum constants." (http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.9)
    As for the problems of memory usage, how big are these strings anyway?
    The advantages of using enums over static final strings are discussed in the "technotes" accompanying 1.5 http://java.sun.com/javase/6/docs/technotes/guides/language/enums.html They list the following as problems with the static final "antipattern"
      * It is not typesafe (methods that expect one of your constants can be sent any old string)
      * There is no name space - so you must continually be sure that your constants don't have names that may be confused
      * Brittleness. Your strings will be compiled into the clients that use them. Then later you add a new constant...
    �  * Printed values will be uninformative. Perhaps less of a problem for Strings, but, still, simply printing the string will leave its semantic significance obscure.

  • Using enum's from one class in another?

    heya,
    I have two classes, Predator and Simulation, and Predator has an public enum 'target' inside it.
    Simulation needs to use a switch statement based on target (Simulation contains a list of Predators, and I'm returning type target to Simulation), but I am getting errors when compiling the two classes from the commandline (for some weird reason, it works fine in Eclipse - both classes are in a package 'lepidoptera', which I originally thoguht was the issue).
    Errors are like (5 of these):
    Simulation.java:64: an enum switch case label must be the unqualified name of an enumeration constant
                    case (mimic):Any ideas?
    Thanks,
    Victor

    This works for moi:
    public class Predator {
        public enum Target {SEITAN, TOFU, TEMPEH}
    public class Simulation {
        public static String f(Predator.Target target) {
            switch(target) {
                case SEITAN:
                    return "yuck";
                case TOFU:
                    return "ugh";
                case TEMPEH:
                    return "crikey";
                default:
                    return "nuts";
        public static void main(String[] args) {
            System.out.println(f(Predator.Target.SEITAN));
            System.out.println(f(Predator.Target.TOFU));
            System.out.println(f(Predator.Target.TEMPEH));
    }And do you know that an enum can be a top level class? In other
    words, that you can create the one-line file Target.java:
    public enum Target {SEITAN, TOFU, TEMPEH}

  • BUG: JDeveloper 10.1.3.0.3 EA - Exception in switch using enum

    Hi,
    I was encountered runtime exception in switch statement, if I use enum.
    In the next example the exception:
    Exception in thread "main" java.lang.ClassFormatError: Invalid field attribute index 0 in class file com/crcdata/enumtest/client/EnumTest$1
         at java.lang.ClassLoader.defineClass1(Native Method)
         at java.lang.ClassLoader.defineClass(ClassLoader.java:620)
         at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
         at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
         at java.net.URLClassLoader.access$100(URLClassLoader.java:56)
         at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
         at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
         at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
         at com.crcdata.enumtest.client.EnumTest.main(EnumTest.java:13)
    is thrown on line "switch (season)".
    package com.crcdata.enumtest.client;
    public class EnumTest {
      public enum Season { WINTER, SPRING, SUMMER, FALL }
      public EnumTest() {
      public static void main(String[] args) {
        EnumTest enumTest = new EnumTest();
        Season  season = Season.WINTER;
        switch (season) {
          case WINTER:
            System.out.println("Season: " + season.name());
            break;
          default:
            System.out.println("Another season");
            break;
    }This exception occur only if use ojc compiler. The javac compiler is OK.
    Versions:
    JDeveloper 10.1.3.0.3 EA
    J2EE 1.5.0_05
    Regards,
    Petr

    Thanks for reporting this. I filed bug 4720493 on this.

  • How do I switch my apple Id I use in the iTunes store to the one I have on iCloud?

    how do I switch my apple Id I use in the iTunes store to the one I have on iCloud?

    You can simply sign out and sign in with the different ID. However, if you have any protected media - movies, or songs purchased before they stopped protecting them - you will not be able to play them, so in that case you are rather stuck.
    You can't merge accounts or transfer iTunes purchases from one Apple ID to another: but there is no problem about using two IDs. Use your iCloud ID for iCloud for syncing email, contacts, calendars, bookmarks, and PhotoStream; use your other Apple ID as before for iTunes, iTunes in the Cloud and iTunes Match.
    There's no conflict about doing this, and you won't even notice as Keychain will log you in with the correct ID in each case. It's also better security not to have your iTunes login also your email address, given the number of complaints about hacked iTunes accounts.

  • After ios7 update my iphone is like android os dead slow processing , too fast battery drain,calling process is too low where is apple brand going my friends 11 members using iphone all are got this problem one thing fans like me y they spoil his name ??

    after ios7 update my iphone 4 is like android os dead slow processing , too fast battery drain,calling process is too low where is apple brand going my friends 11 members using iphone all are got this problem one thing apple have unique and unique fans like me why they spoil their name like this update iam too disappointed iam not say for oppose apple iam say for feedback to grow apple in world because i love apple more please solve it
                       by real customers
    iPhone 4, iOS 7, iam apple suporter

    please help me after ios7 update my phone is tooo slowww i want my old iphone                         

  • Hi I'm using iPad.i would like to purchase one of my game but I couldn't,because I don't know the answer to the question.like where was your first job and where was your favorite job.would you please help me.thank you

    Hi I'm using iPad.i would like to purchase one of my game but I couldn't,because I don't know the answer to the question.like where was your first job and where was your favorite job.would you please help me.thank you

    See Kappy's great User Tips.
    See my User Tip for some help: Some Solutions for Resetting Forgotten Security Questions: Apple Support Communities https://discussions.apple.com/docs/DOC-4551
    Rescue email address and how to reset Apple ID security questions
    http://support.apple.com/kb/HT5312
    Send Apple an email request for help at: Apple - Support - iTunes Store - Contact Us http://www.apple.com/emea/support/itunes/contact.html
    Call Apple Support in your country: Customer Service: Contacting Apple for support and service http://support.apple.com/kb/HE57
     Cheers, Tom

  • Dual Apple Cinema Studio Displays where one uses DVI-to-ADC adapter

    I have an Apple Power Mac G4 MDD dual 1.25 GHz desktop with 2GB RAM running OSX Tiger 10.4.
    It is supporting two Apple Cinema Studio LCD flat panel 17" displays simultaneously.
    Currently, it has three internal hard drives and one SuperDrive.
    I use this computer exclusively for my home recording studio for music production.
    My main computer applications are therefore, Pro Tools LE 7.4, Steinberg Cubase, and Reason 3.0.
    Also, I have the full Microsoft Office Suite, but rarely use Word, Excel, PowerPoint and Access.
    To drive the dual displays, I am using a ATI Radeon 9000 Pro which has one ADC port and one DVI port. Therefore, I am using a DVI-ator adapter to connect one of my ADC displays to the DVI port.
    Yesterday, while recording, one of the two displays developed a broad vertical band (approx 4" of black with thin red, green and blue vertical lines). The other display was fine, however.
    I decided to shut down my PowerMac G4 and disconnect the DVI-adapted display and re-boot with only the display that was connected to the ADC port. The Power Mac G4 booted up fine and ran only its display on this particular monitor.
    However, within 5 minutes, the screen re-developed the broad black vertical band with thin red, green and blue lines running up-and-down as before. Therefore, I shut it down and re-booted again. This time, it never booted back up. Rather, its progress indicator (clock picture moving in clockwise diagram kept on spinning around & around, but never booted-up.
    What does this symptom indicate?
    How can I boot-up from the SuperDrive?
    Is there some special combination of hot keys to get to its setup mode (like in Windows)?
    From these symptoms, is my PowerMac G4 MDD fixable?

    Hi-
    Welcome to Discussions!
    It could be that your graphics card has bit the dust.
    To boot to the OS install disc from the optical drive, hold the C key when powering up. This should bring you to the installer. In the window after selection of your desired language, from the menu bar, you canselect Utilities/Disk Utility. From there, run Repair Disk on the hard drive to insure the integrity of the hard drive.
    My computer won't turn on
    Now, if you are able to boot, but no video is displayed, then your graphics card is probably dust.
    My computer displays no video
    If you have a copy of the Apple Hardware Test, it would be good to run that, to verify the hardware.
    If you don't have the AHT, you can download it, and burn it to CD, and run from that:
    Apple Hardware Test

  • How to know the point where one menu popUp is showed ?

    hi,
    I need know the point where one popUp menu is showed, but I have problems to do it....
    I can install actionListener for method actionPerformed of class AbstractAction but the event I get does not able to say the point...
    In the documentation, I read it is possible install a listener for the mouse and select the popUpMenu with the condition
    "if (e.isPopupTrigger())"
    but it is not confortable to do it and in that case it is not easy too to manage the choice for the item selected...
    Some advice please ?
    I write down the code I use...
    thank you to have one answer..
    regards tonyMrsangelo
    import java.awt.AWTEvent;
    import java.awt.event.*;
    import javax.swing.*;
    enum OpzPopMenu
    {NuovoAppuntamento, CancellaAppuntamento, SpostaAppuntamento};
    public class MenuPopUpTestOne {
        public static void main(String[] args) {
            MenuFrameXmenuTestOne frame = new MenuFrameXmenuTestOne();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
    A frame with a sample menu bar.
    class MenuFrameXmenuTestOne extends JFrame {
        JPopupMenu popupMenu;
        public static final int DEFAULT_WIDTH = 300;
        public static final int DEFAULT_HEIGHT = 200;
        public MenuFrameXmenuTestOne() {  // costruttore
            setTitle("MenuTest");
            setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
            popupMenu = new JPopupMenu();
            Action nuovo = new PopupMunuAction("nuovo");
            Action sposta = new PopupMunuAction("sposta");
            Action cancella = new PopupMunuAction("cancella");
            JPanel jp = new JPanel();
            add(jp);
            // item1
            JMenuItem item1 = new JMenuItem(OpzPopMenu.NuovoAppuntamento.toString());
            item1.addActionListener(nuovo);
            popupMenu.add(item1);
            // item2
            JMenuItem item2 = new JMenuItem(OpzPopMenu.SpostaAppuntamento.toString());
            item2.addActionListener(sposta);
            popupMenu.add(item2);
            //item3
            JMenuItem item3 = new JMenuItem(OpzPopMenu.CancellaAppuntamento.toString());
            item3.addActionListener(cancella);
            popupMenu.add(item3);
            jp.setComponentPopupMenu(popupMenu);
            enableEvents(AWTEvent.MOUSE_EVENT_MASK);
        // aggiungere il popupMenu FINE   -----------------
        } // costruttore
    * Serve per gestire il menu popUp
    class PopupMunuAction extends AbstractAction {
    //    String itemOne = "nuovo";
    //    String itemTwo = "cancella";
    //    String itemTree = "sposta";
        public PopupMunuAction(String nome) {
            super(nome);
        public void actionPerformed(ActionEvent e) {
            String command = e.getActionCommand();
            if (command.compareTo(OpzPopMenu.NuovoAppuntamento.toString()) == 0) {
                JOptionPane.showMessageDialog(null, "NUOVO  one");
            if (command.compareTo(OpzPopMenu.SpostaAppuntamento.toString()) == 0) {
                JOptionPane.showMessageDialog(null, "SPOSTA  one");
            if (command.compareTo(OpzPopMenu.CancellaAppuntamento.toString()) == 0) {
                JOptionPane.showMessageDialog(null, "CANCELLA  one");
    } // inner class PopupAction

    tonyMrsangelo wrote:
    I need know the point where one popUp menu is showed, but I have problems to do it....Do you mean where the JPanel was clicked, or where the pop up appears on the screen.
    If you mean where the panel was clicked, then it's as simple as adding this to your program:
            jp.addMouseListener(new MouseAdapter()
                @Override
                public void mousePressed(MouseEvent e)
                    if (e.getButton() == MouseEvent.BUTTON3) // if right clicked
                        // do whatever in here with the e.getX() and e.getY() results
                        System.out.println("[" + e.getX() + ", " + e.getY() + "]");                   
            });

  • How to use * / - + in a switch statement?

    So I wrote a calculator program (im just learning Java).
    As a beginner I used the (press 1 for +, press 2 for - etc) now I want to go back and actually parse the real symbils * / - + and use those...
    I am using JOptionPane library for getting numbers and stuff.. (inputting them as String then converting to doubles)...
    How do I go about the operator symbols though? I can grab as as string no problem.. but then what?
    Ive been trying to figure out how to make a switch statement.. but case *: doesnt work.. it doesnt like the *. Cant convert that to an into or a double (at least I dont think you can?) or is switch statement a bad way to go in this case?
    Any help would be appreciated. :)

    endasil wrote:
    I should mention that it's extremely easy to form a switch statement that wouldn't have a performance benefit, by making the options very sparse. Like this:
    int i = 1000;
    switch ( i ) {
    case 1:
    break;
    case 1000:
    break;
    }Since this is not going to be implemented as a branch table (given the values are so sparse) it probably provides no benefit.
    enums, on the other hand, will be extremely fast in a switch since their integer values (ordinals) are packed as tightly as possible, starting at 0, by the compiler.
    I wonder how Strings will fare in this regard. I suppose if the compiler mods the hashCode, it can pack the possible values fairly tightly. Also, I presume that the cases will have to be compile-time constants.
    But the weirdest part to me is that it'll be actually computing the hash code of Strings at compile time. At first I thought this was reasonable when I discovered that String.hashCode's result was specified by the JLS [http://java.sun.com/docs/books/jls/first_edition/html/javalang.doc11.html#14460]. However, following JLS 1, those sections have been removed. So where is the specification for Java libraries now? Is it simply the Javadoc (String#hashCode()'s Javadoc does specify the actual result of computation)?
    Hmmm... The cases have to be compile-time constants, so that means strings will be in the constant pool, so I guess the compiler will build the lookups based on something that won't change for a given compiled .class file, regardless of which JVM loads it.

  • Switch on Strings - It's not what you think (Don't Shoot Me!)

    I recently decided to undertake an FAQ on the switch statement - how it works, why it works the way it works, when to use it, when not to, how to work without it, and ... here's the kicker ... WHY the rules are so restrictive.
    So, I've been doing some research, and seen some very good reasons provided by developers on why only integers and variants of integers (auto-unboxable versions, or widenning conversions), plus enums, are allowed.
    I've search this forum, and I've seen the topic beaten to death MANY MANY times. I've search other forums, however, and I've been apalled to see so much support for actually changing the specification for switch.
    I've search google, and not found much useful.
    I've search the bug database, and found several bug submissions that are really feature requests. Each has been denied, but with no explanation, nor even the name or initials of the engineer who evaluated the bug.
    I've looked for ANY sort of FORMAL discussion or debate that included sun, java.net, or the JCP, but not found any.
    There are people who have said that with the introduction of linguistic support for Enums in Switches, Strings could have been done at the same time. While I'm glad that they were NOT, I thought I might be able to find something on-line that explained the reasons why not. I expected to find either a dialog or technical paper covering the topic. But I found nothing.
    Does anybody know of any formal discussion that occured on the topic?
    Also, if anybody cares to suppliment my list of reasons, that would be great. Or if anybody thinks there is a logical flaw with one of my reasons, and thinks I should omit or revise it, please also tell me. Thanks! Here's what i have so far:
    - C++ didn't
    - should use .equals or .equalsIgnoreCase?
    - underlying mechanism in byte code is an integer look up table (should language be based on byte code, or vice-versa? not very strong argument)
    - some have suggest hashCode -> but not set in stone (in fact, it changed in version 1.2), and not necessarily unique
    - virtual machine would need to be aware of .equals function (is it already?)
    - switch is not good OO, but is substitute, for use with primitives.
    - switch is meant for enumerable types (loose definition -- all integers could be listed, it would just take a while), and String is not an enumable type.
    - Adam

    Ada couldn't use Strings, but did allow ranges in the cases, as well as "or". (These examples are from the web, but I used to program in Ada.)
         case Today is
              when Mon        => Compute_Initial_Balance;
              when Fri        => Compute_Closing_Balance;
              when Tue .. Thu => Generate_Report(Today);
              when Sat .. Sun => null;
           end case;
          case Bin_Number(Count) is
              when 1      => Update_Bin(1);
              when 2      => Update_Bin(2);
              when 3 | 4  =>
                 Empty_Bin(1);
                 Empty_Bin(2);
              when others => raise Error;
           end case;
      case A is                      -- Execute something depending on A's value:
        when 1          => Fly;      -- if A=1, execute Fly.
        when 3 .. 10    => Put(A);   -- if A is 3 through 10, put it to the screen.
        when 11 | 14    => null;     -- if A is 11 or 14, do nothing.
        when 2 | 20..30 => Swim;     -- if A is 2 or 20 through 30, execute Swim.
        when others     => Complain; -- if A is anything else, execute Complain.
      end case;

  • HT5622 I'm trying to do my updates in the App Store and it keeps telling me that my account is not valid in the us stores and I must switch to the Canadian one. How do I do that?

    I'm trying to do updates in the App Store and it keeps telling me that my account is not valid for use in a US store and I must switch t the Canadian one. How do I do that?

    Change App Store
    1. Tap "Settings"
    2. Tap "iTunes & App Stores"
    3. Tap on your Apple ID
    4.Tap "View Apple ID"
    5. Enter your user name and password.
    6. Tap "Country/Region."
    7. Tap "Change Country/Region"
    8. Select the region where you are located.
    9. Tap "Done".

Maybe you are looking for