Clarification regarding switch case

final int a = 1;
final int b;
b = 2;
int x = 0;
switch (x) {
case a:
case b:why is this code showing an error constant expression required in the case b: line even after i assaigned a value to b.

so in the @OP's code
a is "compile-time" constant, right?
and b is just a common 'ole garden "runtime constant"...
OK... Cool... I never would have thought of making such a distinction.... but cool. Thanks.
Except... But, but, why does the compiler require a compile time constant... I get that it requires a "switchable" type at compile time, but why can't it delay assigning the value to the case until runtime?
Is it just that it's possible that the case variable may not have been assigned a value? Or is there more going on behind a switch statement than I think... to the JLS...
Thanx. Keith.

Similar Messages

  • Problems with a result in a switch/case control statement

    I am having troubles with a switch/case statement in which I am trying to get a result returned from different operators. The problem is that the result always returns 0 no matter what I put in the driver class.
    The class where the result needs to be returned looks like this:
    public class Calculator
         private int num1;
         private int num2;
         private char operator;
         private int result;
         public Calculator(int num1, char operator, int num2)
              this.num1 = num1;
              this.operator = operator;
              this.num2 = num2;
         } // end constructor
         public int getNum1()
              return num1;
         public char getOperator()
              return operator;
         public int getNum2()
              return num2;
         public int getResult()
              return result;
         public int calculate()
              switch(operator)
                   case '+':
                        int result = num1 + num2;
                        break;
                   } // end case '+'
                   case '-':
                        int result = num1 - num2;
                        break;
                   } // end case '-'
                   case '*':
                        int result = num1 * num2;
                        break;
                   } // end case '*'
                   case '/':
                        int result = num1 / num2;
                        break;
                   } // end case '/'
                   case '%':
                        int result = num1 % num2;
                        break;
                   } // end case '%'
              } // end switch
              return result;
         public String toString()
              String message = (num1) + " " + (operator)
                                  + " " + (num2) + " " + "=" + " " + result + "\n";
              return message;
    } // end class
    The driver class looks like this:
    import javax.swing.JOptionPane;
    import java.lang.StringBuffer;
    public class CalculatorApp
         public static void main (String[] args) // begin main
              String choice = "";
              while (!(choice.equalsIgnoreCase("x"))) // begin while loop
                   String number1 = JOptionPane.showInputDialog(
                                  "Enter a positive integer: ");
                   String operatorInput = JOptionPane.showInputDialog(
                                  "Enter operator (+, -, *, /, %): ");
                   String number2 = JOptionPane.showInputDialog(
                                  "Enter another positive integer: ");
                   int num1;
                   char operator;
                   int num2;
                   num1 = Integer.parseInt(number1);
                   operator = operatorInput.charAt(0);
                   num2 = Integer.parseInt(number2);
                   Calculator calculator = new Calculator(num1, operator, num2);
                   String message = calculator.toString() + "\n"
                                       + "Press Enter to conitnue or 'x' to exit.";
                   choice = JOptionPane.showInputDialog(message);
              } // end while loop
              System.exit(0);
         } // end main
    any help would be wonderful! I don't know why the result returned is always 0 but it is. Thanks!
    dragwit

    The previous poster is correct. You never call the calculate method. If you don't call it, no one's going to call if for you. This stuff doesn't work by magic. I think you've misunderstood your prof's intent in this regard.
    However, it still won't work with the changes previously suggested, because declaring an int result in the calculate method will hide the instance field of the same name, which is what your getResult() method retrieves. Don't delare result at all in your calculate method.
    That said, it would be architecturally a lot better if the calculate method returned the result rather than storing it back into the instance.

  • BPEL-Instanz dies silent if switch case is true boolean

    Hello,
    it is very curios. I have the following switch case:
    xp20:compare('string1', 'string2') = 0
    or
    string(xp20:compare('string1', 'string2')) = '0'
    The validation is ok, and the compiler compiles with 0 errors / 0 warnings.
    If I try to invoke the process, the instance dies silent.
    If i write 'string1' = 'string' the behavior is as expected and the instance is running.
    What's the reason
    I am using the last stable release version.
    Best regards
    Harald
    Message was edited by:
    user570114
    Message was edited by:
    user570114

    i just tested your case in 10.1.3.x, it works fine for me. i can see "'two strings do not match" in output variable as expected. can you please copy and past your entire switch block.
    here is my test case ( i took the Switch.bpel sample under references directory):
    <switch>
    <case condition="xp20:compare('string1', 'string2') = 0">
    <assign>
    <copy>
    <from expression="'Value is greater than zero'"/>
    <to variable="output" part="payload" query="/tns:resultMsg/tns:valueResult"/>
    </copy>
    </assign>
    </case>
    <otherwise>
    <assign>
    <copy>
    <from expression="'two strings do not match'"/>
    <to variable="output" part="payload" query="/tns:resultMsg/tns:valueResult"/>
    </copy>
    </assign>
    </otherwise>
    </switch>

  • OSB - XQuery - Sample Switch Case

    Hi,
    Can some one pls give me a sample XQ, with Switch Case statement in it, which [Syntax] works in OSB.
    Regards,
    Kaleem...

    I am really afraid that OSB 11g supports XQuery 1.0
    http://download.oracle.com/docs/cd/E21764_01/doc.1111/e15867/xquery.htm
    while the switch statement is introduced only in XQuery 1.1
    http://www.w3.org/TR/2009/WD-xquery-11-20091215/#id-switch
    for the time being, you will have to resort to a cascade of if - then - else :o(

  • How can i subtract two numeric numeric numbers from two switch cases ?

    I have two switch cases in my labView program. I can see them individually on front panel but i need to subtract them and see the result on front panel. 
    Can someone please help me out...
    I am trying to display (Result1 - Result 2) on my front panel. Result1 and Result2 will change with time.
    Regards,
    Awais 
    Attachments:
    play4.vi ‏122 KB

    Move result 1 and result 2 out of the case structures and subract them.
    Right now result 1 or result 2 only get written to if its respective comparison is true.  What do you want to do with the math if either comparison is false?  You haven't defined your problem clearly enough.

  • Some clarifications regarding Aironet settings

    Hi,
    i need some clarifications regarding configuring Aironet stand-alone AP (in this case AIR-LAP1131AG).
    Under Security->SSID Manager:
    what is the purpose of Network ID?
    Under Guest Mode/Infrastructure SSID Settings - what is the purpose of Set Infrastructure SSID?
    and Force Infrastructure Devices to associate only to this SSID?
    Cheers,

    Assign a Service Set Identifier (SSID) to each VLAN configured on the AP. SSIDs enable endpoints to select the wireless VLAN they will use for sending and receiving traffic. These wireless VLANs and SSIDs map to wired VLANs. For voice endpoints, this mapping ensures priority queuing treatment and access to the voice VLAN on the wired network
    For further information click this link,
    http://www.cisco.com/en/US/docs/voice_ip_comm/cucm/srnd/4x/42nstrct.html#wp1098806

  • Troubles with a switch case and final expression?

    Been developing C/C++ for quite a while and still new to Java, and struggling with even the simplest things ... Why isnt this switch/case working?
    have some final "variable" declared in a class contating "constants" like this ...
    public class CConstants {
      public static final int MY_CONSTANT1 = 0x01;
    }Now, If I'm trying to use "MY_CONSTANT1" in a case stateent, I get the error "constant expression required" ?
    CConstants c = new CConstants();
    switch(condition){
      case c.MY_CONSTANT1: { //do some work; break; }
      default: { }
    }I thought this would be a nice idea to increase readability as there will be a long switch/case statement.
    Please help!
    Edited by: George.F on Sep 3, 2009 3:07 AM
    Edited by: George.F on Sep 3, 2009 3:08 AM

    You should refer to that constant as CConstants.MY_CONSTANT1.
    Refering to it via a reference to CConstants is possible but strongly discouraged (infact I'd make CConstants non-instantiable by adding a private constructor).
    Other than that your code should work.
    Could you post a SSCCE that demonstrates your problem.

  • I would like to know how can i compare a switch case 1 and case 2 in C# is it possible to do that? obs i am a begginer :)

    i would like to know how can i compare a switch case 1 and case 2 in C# is it possible to do that? obs i am a begginer :) I tried to do it with search and sort but it did not go well

    let me give you an example if you add a word case 1( lagg ord) how can i compare that word with case 2 words ( in case 2  already exist 5 words)
    here is the my program 
    using System;
    namespace ConsoleApplication1
        class Program
            static void Main(string[] args)
                //Meny
                Console.WriteLine("\n HÄNGA GUBBE\n");
                Console.WriteLine(" 1) Lägg till ord");
                Console.WriteLine(" 2) Lista alla ord");
                Console.WriteLine(" 3) Spela");
                Console.WriteLine(" 4) Avsluta");
                bool utgång = false;
                do
                    int Valet;
                    Console.Write("\n\tVälj 1-4: \n ");
                    try
                        Valet = int.Parse(Console.ReadLine());
                    catch (Exception)
                        Console.WriteLine("Du skriver fel character!\n" +
                            "\nSkriv bara mellan 1 och 4");
                        continue;
                    switch (Valet)
                        case 1:
                            Console.WriteLine("\n lägg ett till ord! ");
                          var input = Console.ReadLine();
                            break;
                        case 2:
                            Console.WriteLine("\n Lista med alla ord :\n");
                            string[] array = { " Lev", " Skratta", " Gledje", " Gråt", " Njut" };
                            Array.Sort<string>(array);
                            foreach (var c in array)
                                Console.WriteLine(c);
                            Console.WriteLine("\n");
                            break;
                        case 3:
                            string guesses, bokstäver;
                            Console.Write("\n Hur många fel får man ha? ");
                            guesses = (Console.ReadLine());
                            Console.WriteLine(" Utmärkt, då spelar vi!\n");
                            Console.WriteLine(" Felgisningar :" + "0/" + guesses);
                            Console.Write(" Gissade bokstäver ");
                            bokstäver = (Console.ReadLine());
                            Console.WriteLine("Aktuellt ord");
                            Console.Write("Gissa bokstav : " + bokstäver + " \n");
                            break;
                        case 4:
                            Console.WriteLine("\n  HEJ DÅ! \n");
                            Console.Beep();
                            utgång = true;
                            break;
                        //avbryter while loopen, avslutar spelet
                } while (!utgång);

  • Switch/Case: How to test byte values in hex format

    OK, this may be a silly question, but being new to Java, I can't seem to get this to work.
    I have a byte value that I want to test in a switch/case statement. The value was assigned to the byte in hexadecimal format. However, testing only works if I use the decimal value of the byte!
    What's even stranger: It does work in a simple if/else statement. In my debugging attempts, I discovered this using the following code:
    //*temporary debug routine
    memoryCells[0] = (byte) 0x86; //LDA
    if(memoryCells[0] == (byte) 0x86)
        System.err.println("byte recognized as hexadecimal!");
    else
        if(memoryCells[0] == -122)
            System.err.println("byte recognized as decimal!"); So, this works in an ordinary if/else statement, but why doesn't it also work in the complex switch/case statement? Snippet below:
           switch (currentOpcode)
                case (byte) 0x86:
                    //*LDA immediate (2 bytes, 2 cycles)
                    registerA = b;
                    currentOpcode = 0x00;
                    cycleCounter = 0;
                break;
            }Thanks in advance for any suggestions...

        public static void main(String[] args) throws Exception {
         byte test = (byte)0x86;
         switch(test)
         case (byte)0x86:
                  System.out.println("Success");
              break;
         default:
                  System.out.println("ooops");
        }This works for me.
    ~Tim

  • Switch/case limit

    I am encountering a very strange problem.. after 39 cases in
    my switch case statement the 40th case does not get executed.. the
    code is in my go button and there are like 1000+ lines of code in
    there.. if I replace my 39th case with the 40th it works but it
    doesn't execute anything after that!! is there a limit on the
    number of case statements we can use in action script??? I am
    really confused with this problem...

    no, but there is a byte limit on a single code block ... I
    can't remember the number off hand. So that's probably what's going
    on there, you might want to consider a looping test or using an
    array.

  • Break statement not working in switch case

    Hi,
    I've run into this problem multiple times and have looked up the syntax for a switch statement. The problem with the code below is that when it goes into the first case, it executes the break statement but still executes the next case instead of breaking out of the switch case. Can anyone see whats going wrong?
    try
                switch (columnProps.getCellType())
                     case (ExcelConstants.CELL_TYPE_STRING):
                         excelCell.setCellValue(iterator.getCurrentColumnStringValue());
                         break;
                     case (ExcelConstants.CELL_TYPE_NUMERIC):
                         excelCell.setCellValue(iterator.getCurrentColumnIntValue());
                         break;
    catch (Exception e)
    System.out.println(e.toString()):
           

    it executes the break statement but
    still executes the next case instead of breaking out
    of the switch case. Can anyone see whats going wrong?You can if you put in traces (print statements) in proper places. This will allow you to exactly follow the switch behaviour.

  • Clarification regarding Shadow Table

    Hi All,
    Clarification regarding Shadow Table. FKK_GPSHAD is a shadow table that belongs to Business Partner. The doubts that i have is
    What is Shadow Table?
    What is the purpose of Shadow table?
    Is it correct way to update Shadow table Manually(Not using any BAPi etc....)?
    Is any BAPI available to update The above mentioned Shadow table.
    Thanks in Advance..

    Reclustering InfoCubes:
    With reclustering, the InfoCube fact tables are always completely converted. The system createsshadow tables with a new clustering schema and copies all of the data from the original tables into the shadow tables. As soon as the data is copied, the system creates indexes and the original table replaces the shadow table. After the reclustering request has been successfully completed, both fact tables exist in their original state (name of shadow table) as well as in their modified state with the new clustering schema (name of original table).
    You can only use reclustering for InfoCubes. Reclustering deactivates the active aggregates of the InfoCubes; they are reactivated after the conversion.
    Reclustering DataStore Objects
    Reclustering completely converts the active table of the DataStore object. The system creates a shadow table with a new clustering schema and copies all of the data from the original table into the shadow table. As soon as the data is copied, the system creates indexes and the original table replaces the shadow table. After the reclustering request has been successfully completed, both active tables exist in their original state (name of shadow table) as well as in their modified state with the new clustering schema (name of original table).
    You can only use reclustering for standard DataStore objects and DataStore objects for direct update. You cannot use reclustering for write-optimized DataStore objects. User-defined multidimensional clustering is not available for write-optimized DataStore objects.
    Pls chk this thread:
    Shadow Table?
    http://help.sap.com/saphelp_nw2004s/helpdata/en/47/5cf74153b6ca17e10000000a155106/content.htm
    Hope this helps,
    Reward points...

  • Help with Switch-Case Statement

    How do you get this in a switch-case statement or work with it?
              if (age < 70) {
                        JOptionPane.showMessageDialog(null, "People that are below the 70s are nothing special.");
              else if (age > 69 && age < 80) {
                        JOptionPane.showMessageDialog(null,  "People that are in their 70s are called septuagenarian.");
              else if (age > 79 && age < 90) {
                        JOptionPane.showMessageDialog(null,  "People that are in their 80s are called octogenarian.");
              else if (age > 89 && age < 100) {
                        JOptionPane.showMessageDialog(null,  "People that are in their 90s are called nonagenarian.");
              else (age > 99 && age < 110) {
                        JOptionPane.showMessageDialog(null,  "People that are in their 100s are called centenarian.");
                   }Thanks~

    As per Java Specification, swtich case expects an integer and boolean cannot be used as param for switch.
    In your case switch can be used like this.
    int index = age /10;
    switch(index) {
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
    case 6:
    Your First case
    break;
    case 7:
    your second case
    break;
    case 8:
    third case
    break;
    case 9:
    fourth case
    break;
    default:
    fifth case
    break;
    Take note of the break statements. Its very important. But I wont prefer in this case. Code looks awkward and is not so meaningful.....

  • DoGet method is called 2 times when a switch-case statement is used

    Hello all,
    I have a servlet that, when run from browser, runs the doGet method 2 times.
    I have a switch case statement within the servlet and when I comment out this servlet, it runs 1 time as expected.
    Here is the code:
    public class RSSServlet extends HttpServlet {
        /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
         * @param request servlet request
         * @param response servlet response
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            System.out.println("CALLED SERVLET");
            response.setContentType("text/xml;charset=UTF-8");
            PrintWriter out      = response.getWriter();
            DBQueriesRSS queries = new DBQueriesRSS();
            String queryType     = request.getParameter("queryType");
            String strCount      = request.getParameter("count");
            int count            = (strCount != null && !strCount.equalsIgnoreCase("null") && strCount.length() > 0) ?
                Integer.parseInt(strCount) : 25;
             if(queryType != null && !queryType.equalsIgnoreCase("null") && queryType.length() > 0) {
                System.out.println("IN IF STATEMENT");
                switch(Integer.parseInt(queryType)) {
                    case 1 : out.println(queries.getDefault(count));System.out.println("1");       break;
                    case 11: out.println(queries.getDefault(count));System.out.println("11");       break;
                    case 21: out.println(queries.getTopDaily(count));System.out.println("21");      break;
                    case 22: out.println(queries.getTopWeekly(count));System.out.println("22");     break;
                    case 23: out.println(queries.getTopMonthly(count));System.out.println("23");    break;
                    case 24: out.println(queries.getTopYearly(count));System.out.println("24");     break;
                    case 31: out.println(queries.getTopNDailyBW(count));System.out.println("31");   break;
                    case 32: out.println(queries.getTopNWeeklyBW(count));System.out.println("32");  break;
                    case 33: out.println(queries.getTopNMonthlyBW(count));System.out.println("33"); break;
                    case 34: out.println(queries.getTopNYearlyBW(count));System.out.println("34");  break;
                    default: out.println(queries.getTopWeekly(25));System.out.println("default");    break;
                System.out.println("OUT OF SWITCH");
            System.out.println("OUT OF IF");
            out.close();
        // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
        /** Handles the HTTP <code>GET</code> method.
         * @param request servlet request
         * @param response servlet response
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            processRequest(request, response);
        /** Handles the HTTP <code>POST</code> method.
         * @param request servlet request
         * @param response servlet response
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
           processRequest(request, response);
        /** Returns a short description of the servlet.
        public String getServletInfo() {
            return "Short description";
        // </editor-fold>
    } The results from running this servlet are:
    http://localhost/proxy/RSSServlet??queryType=34&count=66
    CALLED SERVLET
    IN IF STATEMENT
    34
    OUT OF SWITCH
    OUT OF IF
    CALLED SERVLET
    IN IF STATEMENT
    34
    OUT OF SWITCH
    OUT OF IFAnyone see anything obvious?
    TIA!

    in your case you want 'count' to be a class attribute rather than a local variable. But yes, incrementing it each time that the method is called will serve your purpose.

  • Regular expression in a switch case

    Hey guys,
    I have a string "52x + 60" and i want to extract 52x and 60 using regular expressions and a switch case
    Is this the right way of doing it?
    var equation:String = "32x + 5"
    var numberExract:RegExp = /\d+/
    var xExtract:RegExp = /d+/x/
    for(var i:Number=0; i<equation.length; i++)
                        switch(equation.charAt(i))
                                  case numberExtract.exec(equation):
                                  trace("number");
                   break;
                   case xExtract.exec(equation):
                   trace("x");
                   break;
    Because it's not tracing anything when i try

    Here is a quick and dirty approach - can be customized, optimized and more elegant expressions used:
    // equation
    var string:String = "x^2 + 5x + 5 - x7 + 8 / 4";
    // value replacing xs
    var value:Number = 60;
    // replace xs with value
    // if x comes after digit
    string = string.replace(/(?<=\d)x/g, String("*" + value));
    // if x comes before digit
    string = string.replace(/x(?=\d)/g, String(value + "*"));
    // all other xs
    string = string.replace(/x/g, String(value));
    // remove spaces
    string = string.replace(/\s/g, "");
    // get pairs with first level math
    var pattern:RegExp = /(\d+[\*\^\/]\d+)|\D|\d+/g;
    var result:Number = stringToMath(string.match(pattern));
    trace("result", result);
    function stringToMath(match:Array):Number
        // digits surrounding operator
        var pattern:RegExp = /\d+\D\d+/;
        for (var i:int = 0; i < match.length; i++)
            if (match[i].match(pattern))
                match[i] = String(calculate(match[i]));
        trace("loop result", match);
        return calculteSum(match);
    * Calculates sums
    * @param    array
    * @return
    function calculteSum(array:Array):Number
        var result:Number = array[0];
        for (var i:int = 1; i < array.length - 1; i++)
            if (array[i] == "+")
                result += array[i + 1];
            else if (array[i] == "-")
                result -= array[i + 1];
        return result;
    * First level math
    * @param    string
    * @return
    function calculate(string:String):Number
        var operator:RegExp = /[\+\*\/\^\-]/g;
        var digits:Array = string.match(/\d+/g);
        var num:Number = 0;
        if (digits && string.match(operator) && digits.length > 1)
            switch (string.match(operator)[0])
                case "*":
                    num = digits[0] * digits[1];
                    break;
                case "/":
                    num = digits[0] / digits[1];
                    break;
                case "+":
                    num = digits[0] + digits[1];
                    break;
                case "-":
                    num = digits[0] - digits[1];
                    break;
                case "^":
                    num = Math.pow(digits[0], digits[1]);
                    break;
        return num;

Maybe you are looking for