Switch with string

hi, i've been reading a few of the previous discussions on usability of switch with string. why can't switch be made to work with all datatypes? is it really such a big deal? if there is a serious reason for not letting switch work with all datatypes pls bring it to the open. i'm an avid java guy and hope that there's the least amount of ambiguity with this beautiful language.
sunny

switch only works for primitive numersic types.
I am not positive about the reason for this.
One guess is that for switch to work with Objects it would have to automatically evaluate using the equals() method. In general the Java language doesn't allow constructs that aren't explicit. This is the kind of thing the throw into C#.
It would be nice if you could do a switch of the references. That way you could use switch with typesafe enumerations.

Similar Messages

  • Java Switch Statement with Strings

    Apparently you cant make a switch statement with strings in java. What is the most efficient way to rewrite this code to make it function similar to a swtich statement with strings?
    switch (type){
                   case "pounds":
                        type = "weight";
                        break;
                   case "ounces":
                        type = "weight";
                        break;
                   case "grams":
                        type = "weight";
                        break;
                   case "fluid ounces":
                        type = "liquid";
                        break;
                   case "liters":
                        type = "liquid";
                        break;
                   case "gallons":
                        type = "liquid";
                        break;
                   case "cups":
                        type = "liquid";
                        break;
                   case "teaspoons":
                        type = "liquid";
                        break;
                   case "tablespoons":
                        type = "liquid";
                        break;
              }

    I'd create a Map somewhere with entries "liquid", "weight", etc.
    public class Converter {
        private static Map<String, List<String>> unitMap = new HashMap<String, List<String>>();
        private static String[] LIQUID_UNITS = { "pints", "gallons", "quarts", "millilitres" };
        private static String[] WEIGHT_UNITS = { "pounds", "ounces", "grams" };
        static {
            List<String> liquidUnits = new ArrayList<String>();
            for (int i = 0; i < LIQUID_UNITS.length; i++) liquidUnits.add(LIQUID_UNITS));
    unitMap.put("liquid", liquidUnits);
    ... // other unit types here
    public String findUnitType(String unit) {
    for (String unitType : unitMap.keySet()) {
    List<String> unitList = unitMap.get(unitType);
    if (unitList.contains(unit))
    return unitType;
    return null;
    It might not be more "efficient", but it's certainly quite readable, and supports adding new units quite easily. And it's a lot shorter than the series of if/else-ifs that you would have to do otherwise. You'll probably want to include a distinction between imperial/metric units, but maybe you don't need it.
    Brian

  • Switch with a string?

    Is it possible to do a switch with a String?
    The following does not seem to work
    String a = "bubble";
    switch(a) {
      case "tricks":
        System.out.println("This trick doesn't seem to work");
        break;
      case "bubble":
        System.out.println("It's gone and burst my bubble");
        break;
    }Any ideas?
    Thanks
    Bubble

    Brannor:
    E.g. switch (testString.hashCode()) {
    case ("case 1".hashCode())...This won't work. You need a constant expressions for the cases, a method like hashCode() won't work there.
    Yogee:
    1. Different Strings are not guaranteed to generate different hashcodes.True, but its such a unlikely event that the strings' hashcodes will be equal that someone would still be able to do this reasonably in some situations. but I wouldn't do this in my code
    2. The algorithm used to generate the hashcode is not guaranteed to be the same on different platforms.There is a String hashcode formula, and its not ambiguous. The method is implemented entirely in java and so it will be the same on different platforms. Object.hashCode() though can be different on different platforms.
    3. The algorithm used to generate the hashcode is not guaranteed to be the same on different
    java versions.We can use that argument against writing anything in the API though, since the language can always change. Has Sun ever indicated that they might want to change the API specs for Strings's hashCode?

  • 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.

  • Unmanaged switch with CDP?

    I am trying to find an unmanaged cisco switch that has cdp.  Technically the switch doesn't have to be unmanaged, but I am looking for a cheep switch with only 5-10 ports that also has cdp.  I can't be sure if the small cisco SD series switches, formerly s***sys, have cdp now or not.

    Brannor:
    E.g. switch (testString.hashCode()) {
    case ("case 1".hashCode())...This won't work. You need a constant expressions for the cases, a method like hashCode() won't work there.
    Yogee:
    1. Different Strings are not guaranteed to generate different hashcodes.True, but its such a unlikely event that the strings' hashcodes will be equal that someone would still be able to do this reasonably in some situations. but I wouldn't do this in my code
    2. The algorithm used to generate the hashcode is not guaranteed to be the same on different platforms.There is a String hashcode formula, and its not ambiguous. The method is implemented entirely in java and so it will be the same on different platforms. Object.hashCode() though can be different on different platforms.
    3. The algorithm used to generate the hashcode is not guaranteed to be the same on different
    java versions.We can use that argument against writing anything in the API though, since the language can always change. Has Sun ever indicated that they might want to change the API specs for Strings's hashCode?

  • Using Catalyst 3550 Switch with Linksys Home Router and Cable Internet

    I've about pulled what little hair I have out of my head on this one, and need some configuration help.
    I have a Cisco Catalyst 3550 switch with five Windows 7 desktops, an Avaya PBX and five Avaya IP phones attached.  All of these devices are on a 192.168.0.0/24 subnet, and are communicating properly.  I will refer to this as network # 1. I also have SEPARATE network, we'll call network # 2, using AT&T ADSL service and a Netgear 4-port/wireless router/ADSL modem combo device, which is functioning properly with a couple of other Windows 7 desktops over its own wired Ethernet network, using DHCP, and also on a 192.168.0.0/24 subnet.  I thought it would be a simple integration, just plugging one of the 3550's ports to one of the DSL router's ports, in order to give the five Windows 7 desktop computers on network # 1 internet access via the DSL modem. Guess I was wrong.  When I connect the two switches together, although I get a good connectivity (green lights on both ports) and am able to ping the DSL router's gateway address (192.168.0.252) from network # 1's computers, the computers on network # 1 cannot access the internet. Also, the working computers on network # 2 lose their internet access as long as the two switches are connected together. I am not a Cisco guru, but there's got to be a way to make this scenario work.  Can someone provide me with a 3550 configuration that will allow me to extend my internet service from network # 2 on the DSL router to my 3550 switch and their computers?  Here's what I am looking for:
    INTERNET ---> ADSL MODEM ---> NETGEAR ROUTER ---> CISCO 3550 SWITCH ---> NETWORK DEVICES WITH INTERNET ACCESS

    The Netgear router is probably what's doing the natting. Is the 3550 configured for routing or is it straight L2? If you have the 3550 configured as L3, then it's going to be easy to do what you want. Just add a static route on the Netgear to point the subnet that it doesn't know about to the 3550. For example, if the Netgear is addressed at 192.168.1.1 and the Cisco 3550 is addressed at 192.168.1.2, but it also knows about the 192.168.0.0/24 (separate vlan), then you would put a static route on your Netgear for 192.168.0.0/24 to go to 192.168.1.2.
    The way that I would do it is to create a separate vlan on the 3550 and assign an address to it. Once you do that, make the port that the other switch connects to an access port of that vlan. (It would need to be on the same subnet as the existing equipment.) All of your devices would use it as a default gateway and then you would do the rest as above. You could also use RIP between the Netgear and Cisco if you can't do static routing.
    HTH,
    John

  • After installing an update I am no longer able to hear sound out of my speakers. A red light comes on where the headphone jack is. I have already attempted to trip to switch with a wooden toothpick in the headphone jack but have not had luck.

    after installing an update I am no longer able to hear sound out of my speakers. A red light comes on where the headphone jack is. I have already attempted to trip to switch with a wooden toothpick in the headphone jack but have not had luck.

    Have you gone into system prefs nad made sure that the headphone port is set to audio out. And not audio in.
    Also make sure that you are selecting built in speakers for your audio output.
    If that does not fix it try doing a Pram reset.
    Shut your mac down.
    Press the startup button.
    Hold down the following keys. Command Option P and R. Wait till you hear the chime 2 times. Then let go. See if that fixes it.

  • Toggle switches with if else

    I am trying to toggle various switches based off of others and am wondering how I can go about this. For example, if switch A is on, B should toggle off. If I toggle B on, A should toggle off. Any help in doing this would be appreciated. Thanks.

    Thank you for an easy question..... 
    There's a mode in the Switch options that allows you to create a single switch with two channels, where only one will be on.
    - cj
    Measurement Computing (MCC) has free technical support. Visit www.mccdaq.com and click on the "Support" tab for all support options, including DASYLab.

  • Urgent!!!!!! Issue with String in CO

    Hi All,
    I am learner of OAF.
    I have issue with string while converting into double.
    In AM,
    public String ComputeMarginPercent()
    retrun form.format((55570.0*100)/184.64999999999418);
    in CO..I am getting the value:
    String s1 = (String)oapagecontext.getApplicationModule(oawebbean).invokeMethod("computeMarginPercent");
    here getting value of s1=30,094.77
    I need to convert s1 to double, while converting double its raising error.
    how can I remove comman in (30,094.77) this number..?
    please advise me ..

    Hi Pratap,
    I am new to java ..
    Can you please tell me in step by step..?
    Thanks in advance
    I tried like /..
    String str= "30,094.77 ";
    char[] chars = str.toCharArray();
    String s = String.copyValueOf(chars);
    System.out.println(s);
    Still displaying value as 30,094.77 (with comma)
    Edited by: user633508 on Nov 21, 2008 2:55 AM

  • Problem with String variable

    I am new to Java Programming.
    I have a line of code that works and does what is supposed to.
    faceData.getProfile("Lisa").removeFriend("Curtis");
    If I assign the strings to variables such as-
    String name = "Lisa";
    String fName = "Curtis";
    and then plug those into the same line of code, it does not work
    faceData.getProfile(name).removeFriend(fName);
    What could be causing the problem?
    I even added some lines to print out what is stored in the variables to verify that they are what they should be, but for some reason the variables do not work while putting the strings in quotes does. Any ideas?

    I guarantee that something about your assertions are incorrect. Those variables are either not equal to the values you claim, or something else is going on. But it's not a problem with string variables versus string constants.
    Edit: My best guess in lack of a real example from you, is that the strings in question have non-printable characters in them, such as trailing spaces or line feeds.

  • Little problem with Strings.

              I have an little problem with Strings, i make one comparision like this.
              String nombre="Javier";
              if( nombre.equalsIgnoreCase(output.getStringValue("CN_NOMBRESf",null)) )
              Wich output.getStringValue("CN_NOMBRESf",null) is "Javier" too, because I display
              this before and are equals.
              What I do wrong?.
              

    You are actually making your users key in things like
    "\026"? Not very user-friendly, I would say. But
    assuming that is the best way for you to get your
    input, or if it's just you doing the input, the way to
    change that 4-character string into the single
    character that Java represents by '\026', you would
    use a bit of code like this:char encoded =
    (char)Integer.parseInt(substring(inputString, 1),
    16);
    DrClap has the right idea, except '\026' is octal, not hex. So change the radix from 16 to 8. Unicode is usually represented like '\u002A'. So it looks like you want:String s = "\\077";
    System.out.println((char)Integer.parseInt(s.substring(1), 8));Now all you have to do is parse through the String and replace them, which I think shouldn't be too hard for you now :)

  • Regex with strings that contain non-latin chars

    I am having difficulty with a regex when testing for words that contain non-latin characters (specifcally Japanese, I haven't tested other scripts).
    My code:
    keyword = StringUtil.trim(keyword);
    //if(keywords.indexOf(keyword) == -1)
    regex = new RegExp("\\b"+keyword+"\\s*;","i");
    if(!regex.test(keywords))
    {Alert.show('"'+keywords+'" does not contain "'+keyword+'"'); keywords += keyword + "; ";}
    Where keyword is
    日本国
    and keywords is
    Chion-in; 知恩院; Lily Pond; Bridge; 納骨堂; Nōkotsu-dō; Asia; Japan; 日本国; Nihon-koku; Kansai region; 関西地方; Kansai-chihō; Kyoto Prefecture; 京都府; Kyōto-fu; Kyoto; Higashiyama-ku; 東山区; Places;
    When the function is run, it will alert that keywords does not contain keyword, even though it does:
    "Chion-in; 知恩院; Lily Pond; Bridge; 納骨堂; Nōkotsu-dō; Asia; Japan; 日本国; Nihon-koku; Kansai region; 関西地方; Kansai-chihō; Kyoto Prefecture; 京都府; Kyōto-fu; Kyoto; Higashiyama-ku; 東山区; Places; " does not contain "日本国"
    Previously I was using indexOf, which doesn't have this problem, but I can't use that since it doesn't match the whole word.
    Is this a problem with my regex, is there a modifier I need to add to enable unicode support or something?
    Thanks
    Dave

    ogre11 wrote:
    > I need to use refind to deal with strings containing
    accented characters like
    > ?itt? l?su, but it doesn't seem to find them. Also when
    using it with cyrillic
    > characters , it won't find individual characters, but if
    I test for [\w] it'll
    > work.
    works fine for me using unicode data:
    <cfprocessingdirective pageencoding="utf-8">
    <cfscript>
    t="Tá mé in ann gloine a ithe;
    Nà chuireann sé isteach nó amach
    orm";
    s="á";
    writeoutput("search:=#t#<br>for:=#s#<br>found
    at:=#reFind(s,t,1,false)#");
    </cfscript>
    what's the encoding for your data?

  • Change a 3560 Switch with Lifetime Waranty

    A simple question:
    Our client has 3560X Switches with a limited lifetime warranty. The Cisco Partner with whom they had the contract before bought the equipment, and they did not end up on good terms. One of the devices died the other day. My question is - how do we replace it now?
    Thanks

    I wish... here is the answer I got from TAC: "in this case there is nothing we can do to replace it as per Cisco policies and procedures customer has to engage his reseller for support."
    So disappointing... Now I need to call the client and tell them they need to throw the lifetime warranty switch away and buy a new one... 

  • HDMI switching with YV box - help?

    I am now in the unfortunate position of having a TV with only one HDMI input but currently have two boxes (YouView and NowTV) that output HDMI. The one scart input is used by the DVD player and I'm aware of scart-switch problems where YV boxes are concerned too.
    I bought a Duronics HDMI auto-switcher, it has three inputs and one output. I connected it up and the NowTV box displayed its bouncing logo fine. I switched on the YV box and got a pink screen. I tried unplugging the NowTV box from the mains, unplugging the HDMI lead etc. Cycling through the inputs using the manual switch - still the same pink screen, turned box on-off etc.
    Has anyone managed to use a HDMI switcher and if so how or which one and if it does work, does it always work without a problem? 
    For info: I have a BT supplied box (the first one they sent out, Humax ..), power set to the quicker starting one (eco-mode: Low??)

    I use a Thor combined HDMI/Optical switch with the YV box with no problem. Occasionally see a flash of pink when it switches then it settles down.
    Does this happen if you switch first before turning on the YV box (does your auto-switcher let you manually override to do this)?
    Have you re-tried plugging the HDMI lead direct into the TV as it maybe just a co-incidence this started happening when you introduced the switch?
    One other thing I suggest you try is swapping the HDMI leads between the YV box and the Now TV device.

  • Operating a SG200-08 switch with case removed.

    I am going to be putting an SG200-08 (8 port switch) inside a 2U rackmount chassis.
    To enhance cooling I thought I would remove the outer case.
    Are there, or would there be any issues with using the switch with the cover removed?
    Thanks
    Glen

    Hi Glen, the first issue would be, the warranty is void and you're not entitled to any support. The second issue would be static electricity and environmental concerns. The third issue would likely be your property insurance.
    It is highly against recommendation to alter or modify these units.
    -Tom
    Please mark answered for helpful posts

Maybe you are looking for

  • Samsung Fascinate, problems with playing music via USB port on car stereo

    Before the update, I could play the music files on my Fascinate via the USB port on my Kenwood stereo, and control basic functions such as skip, pause etc.  Now, my stereo does not recognize the device, and cannot read the files.  I went to local Ver

  • IPad Wi-Fi + 3G is connected to Wi-Fi 3G turned off can't connect.

    I have the original iPad and have owned it for quite a while. This seem to have started within the last few weeks. It may have something to do with the upgrade to 4.3.1, I don't know. But I have been told by AT&T twice now in about three weeks that I

  • New Fields For Free Goods Determination

    Hi everyone.  We need to add a new field for FG determination.  According to the documentation in SPRO, the new field should be added in SE11 KOMK under include KOMKZ for free goods.  However there is no KOMKZ include in KOMK.  How is this supposed t

  • Updating software without admin rights?

    a few months ago, my mac was assimilated into a Windows active directory and all my admin rights were taken away (security reasons). I am fine with this for the most part, but I do have one problem. I can no longer update my computer's software witho

  • I am not able to unlock my phone.

    I am not able to unlock my phone from screen? Can  someone tell me what could be problem with my phone plz..