Difficulty in using switch-case

I want to display certain labels on the basis of the value supplied in switch .But it's not working . I don't know how to overcome the problem .Kindly guide me.
My page is as follows:
<html>
<head>
</head>
<body>
<%!
     int i=1;
%>
<%
     switch(i)
%>
<%
     case 1:
%>
In case 1.
<%
     break;
%>
<%
     case 2:
%>
In case 2.
<%
     break;
     default :
%>
</body>
</html>

The JSP interpreter is putting in statements which makes your code not compile.
This is caused by the carriage returns in your jsp code.
switch(i)
out.print(__constantTable.getString(103)); // *** Syntax: SwitchLabels expected after this token
case 1:
out.print(__constantTable.getString(165));
break;
out.print(__constantTable.getString(98)); // *** unreachable code
case 2:
out.print(__constantTable.getString(166));
break;
default :
}Solution
1 - Don't mix scriptlets and jsp code in this way. Particularly closing %> and then opening again.
The following will work
<%!
int i=1;
%>
<%
switch(i){
case 1:
%>
In case 1.
<%
break;
case 2:
%>
In case 2.
<%
break;
default :
%>2 - a better solution is to use a custom tag, or tag library like JSTL to implement this
<c:choose>
  <c:when test="${i == 1}">In Case 1 </c:when>
  <c:when test="${i==2}"> In Case 2 </c:when>
  <c:otherwise> Default value </c:otherwise>
</c:choose>Cheers,
evnafets

Similar Messages

  • Multiple records using switch case

    Hi...
         I am having input file like
      <?xml version="1.0" encoding="utf-8" ?>
    - <ns1:mt_out xmlns:ns1="http://Block">
    - <Material>
      <Item>0</Item>
      <ItemName />
      <ReqQty>0</ReqQty>
      <AvailQty>0</AvailQty>
      <Cost>0</Cost>
      <suppid />
      <suppname />
      <leadtime>0</leadtime>
      <matname>Y-351</matname>
      <plantloc>2222</plantloc>
      <date>2008-09-30T00:00:00</date>
      <orderqty />
      <warehouseloc />
      <unit>KG</unit>
      </Material>
    - <Material>
      <Item />
      <ItemName />
      <ReqQty>0</ReqQty>
      <AvailQty>0</AvailQty>
      <Cost>0</Cost>
      <suppid />
      <suppname />
      <leadtime>0</leadtime>
      <matname>Y-355</matname>
      <plantloc>1111</plantloc>
      <date>2008-09-30T00:00:00</date>
      <orderqty />
      <warehouseloc />
      <unit>KG</unit>
      </Material>
    - <Material>
      <Item />
      <ItemName />
      <ReqQty>0</ReqQty>
      <AvailQty>1000.000</AvailQty>
      <Cost>0</Cost>
      <suppid />
      <suppname />
      <leadtime>0</leadtime>
      <matname>Y-352</matname>
      <plantloc>1100</plantloc>
      <date>2008-09-30T00:00:00</date>
      <orderqty />
      <warehouseloc />
      <unit>KG</unit>
      </Material>
      </ns1:mt_out>
      In this input file it is having multiple records. Based on the AvailQty, the input file should go to the webservice. If the condition AvailQty is !=0, the the input file should go to the java webservice or else it should go to the .net webservice. In BPM i have used switch step for this. if i give the input file structure like above it is going to the java webservice only. It is not entering to the esle part.
    Could you please help me out in this issue.
    Thanks & Regards,
    Leela

    Hi,
    Having had a look at these blogs:
    Illustration of Multi-Mapping and Message Split using BPM in SAP Exchange Infrastructure
    How to Split Message through BPM in 1:n scenario
    Transformation Step to Implement 1:n Splitting
    I think the best solution for your scenario is the following:
    In your BPM use a TransformationStep that does the multimapping N:1
    And then send the messages individually. You don`t need a Switch Step.
    You should have two Receiver determination.
    1.- File_server --> Integration Process.
    2.- Integration Process --> WebService.
    In the second RD, add two receiver Services (e.g. JAVA_WebService and NET_WebService) and
    use routing roules that checks if AvailQty is !=0. And depending on this condition,
    the message should be sent either JAVA_WebService or NET_WebService.
    Hope this helps you.
    Carlos

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

  • 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);

  • How to use switch statement in JSP?

    Hi,
    I am using switch satement in jsp.
    the code as follows:
    switch(flag)
         case 1: query="select * from cust";
                        break;
         case 2: query="select * from cust where minp="+mini+"and maxp="+maxi;
                        break;
        default: query="";
    out.println(query);but, i am getting some number format exception. I don't know where i am going wrong.
    Please help
    Regards,
    Ashvini

    I got the solution
    Thanks anyways
    Regards,
    AShvini

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

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

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

  • Multiple Column hiding in advance table using Switcher

    Hi All,
    I am having requirement of hiding multiple columns in advance table using swithers.
    Lets says I am searching for the the parties in party search page. If the party is of type person then two columns should be visible one is firstName and LastName.
    and If party is of type organization then firstName and lastName column shpould be hidden and only the PartyName column should be visible.
    Is this possible through switchers if yes please explain?
    Br, 903096

    Hi ,
    This can be done through switcher case , along with switcher you also need to use SPEL binding the each of those attribute
    that you wish to hide .
    Go through delete exercise to understand how to implement switchers case .
    Let me know if you need any help .
    --Keerthi                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • OATS: trying to use switch statement.

    Hi All,
    I am trying to use the case statement in my functional script.
    I am inserting the value in text-box lets say 1 , 2 , 3 ,4.
    and have created the Databank as
    Value in text-box               Name
    1                                      A
    2                                      B
    3                                      C
    i want that when i enter the value in text-box as 1 it should execute some code and if 2 then other code.
    cases will be like
    switch (??)
    case A:
    execute code1
    case B:
    execute code2
    case C:
    execute code3
    My ques is how i can compare the values like :
    if i enter the value 1 in text-box it should take case A, if if i ll enter 2 in text-box it should take case 2.
    I am using this approach so that i can change the values 1 , 2 , 3 in the databank anytime i need and play the script.
    can anyone please tell me how i can do so.
    Thanks in advance.
    Thanks
    Ketan

    Based on my understanding, textbox is an object in additional interface for script selection during playback
    HashMap<String, String> selectScript = new HashMap<String, String>();
                for (int count = 0; count < getDatabank("DataBank Alias Name").getDatabankRecordCount(); count++) {
                    getDatabank("DataBank Alias Name").getNextDatabankRecord();
                    selectScript.put(eval("{{db.DataBank Alias Name.Value in text-box}}"), eval("{{db.DataBank Alias Name.Script Name}}"));
            Get the text entered in textbox and assign to a String, say key
      info("Script selected is - " + selectScript.get(key));
      getScript(selectScript.get(key)).run(1,true,true,true);
    Regards,
    Deepu M
    [email protected]

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

  • Multiple records using switch in BPM

    Hi,
    Below is the input file i am having.
    <?xml version="1.0" encoding="utf-8" ?>
    -<ns2:MT_Receiver xmlns:ns2="File2RFC">
    <Details>
    <Availability>5000.000</Availability>
    <Message />
    </Details>
    <Details>
    <Availability>1000.000</Availability>
    <Message />
    </Details>
    <Details>
    <Availability>0</Availability>
    <Message>Material Test not maintained in plant 1100</Message>
    </Details>
    </ns2:MT_Receiver>
    I want to divide this input file into two parts based on one condition. If the Availability!=0, then it should display the available quantity. or else, it should get suppliers from the webservice.
    For this reqiurement, i have used the switch case. but it is not working. It is considering only the last record, For eg, in this input file the last record is having Availabilty=0. So it should go to webservice and display the suppliers. But all the 3 records are going to the else branch and giving the supplier details.
    Could you please tell how to resolve the issue.the Availability which is present should go to one branch and the remaining records should go to the else branch. Please help me in this regard.

    Hi, Leelaratnam:
    What Anand mentioned is to split the message based on your node of "Details":
    Each "Details" node will generate new message which only have one <Availability> elements (u will need another message type)
    Then you can pass to your webservice, avoid your problem that only last <Availability> passed to webserivce.
    You will have a multi-mapping (1:n)
    in you BPM, you will have transformation step, then a block (ForEach) to process your splitted message one by one.
    Yes, this is one solution.
    Check my previous response, you will just need one mapping program, one transformation step, you can also achieve your purpose. However, in your mapping program, you need to code a UDF to do a lookup.
    Regards.
    Liang

  • Switch case list UI

    Hi!
    For pedagocial and c-like reasons i'd like there to be a "Case-unbundle", which would be very nice if you're only calling sub-vi's in a case e.g.
    Is there any way to create such a thing?
    Instead of the Case-square i want it to be a "Unbundle by name" where i connect each output to my sub-vi's (like a multiplexer) and the appropriate one is called.
    Any ideas?
    /Y
    LabVIEW 8.2 - 2014
    "Only dead fish swim downstream" - "My life for Kudos!" - "Dumb people repeat old mistakes - smart ones create new ones."
    G# - Free award winning reference based OOP for LV

    Well, nice asumptions, but i have another one:
    LabVIEW has a case structure where only one single case is visible at a time. This is a huge difference to C-based languages where a switch-case displayes every case at the same time in a "list".
    I think the question from the OP is: "Is it possible to display a case-structure in LabVIEW 'flattened' so that every case is visible at the same time?"
    And to answer this question: No it is currently not possible, was never possible and hopefully will never be. But you can create a "report" using the print-function and this can automatically create screenshots of each case and display them next to each other..... 
    just my 2cents
    Norbert 
    CEO: What exactly is stopping us from doing this?
    Expert: Geometry
    Marketing Manager: Just ignore it.

Maybe you are looking for

  • DVR capacity

    After erasing all recorded movies from DVR, I check Recorder Status and see "16% used", 84% free". I thought maybe 16% of memory is used to store data regarding Schedule. Then I deleted all schedules to see what happens. It still says the same, i.e.

  • APO CONFIRMING THE QUANTITY THOUGH STOCK IS NOT AVAILABLE

    Hi Friends,                  I have an issue in APO.i have a stock of 360 for material m1.when i tried to create a sales order in r/3 the apo confirming 324 for first time.But when i tried to create another sales order again apo is confirming 324 for

  • Help, my battery died!

    So... I sent in my original battery about this time last year because of the battery recall. After a while I noticed that my new battery overheated a lot more than the original one... probably a lot more prone to fires than the last one. Finally, las

  • Display column name in sql*plus

    Hi, How to display full column name? there are n no of tables, i have to query the tables but i want the column name to be displayed fully. for example SQL> desc control Name Null? Type CODE NOT NULL VARCHAR2(255) LOAD_PERIOD_START_DATETIME DATE SQL>

  • Question about multiple users on pc

    How do i make the same itunes library available on two users accounts on the same pc that has windows 7?