Question about "switch" statement

hi all I am new to Java programming..
I have one problem that is
I would like to use switch statement like below
in the switch statement can we use only integers ?
but i am using string it is not supporting ..
for strings like below what I have to do...
String temp = "str2";
switch(temp){
case "str1":
case "str2":
case "str3":
case "str4":
please send the solution if anyone knows
thanks

What do you mean by a smart hash?At least smarter than String.hashCode ().
Don't think so - char, byte, short, or int.You're correct - seems I've got to test things before I post. So it's safe to say that a switch works on anything that can be treated as an int?

Similar Messages

  • Newbie question about switch statement

    Lets say you have a loop and inside the loop you have a switch statement, how do you BREAK out of the outer loop?
    for (i=0....) {
    switch {
    case 11:
    .... some stuff
    break; <==== HOW DO I BREAK OUT OF THE for loop here?

    In standard C and standard C++ the break statement terminates the nearest enclosing loop and only that loop; i.e. control transfers to the first statement following the loop. I think there are C or C++ extensions that allow loop tags which may be used with a break to specify which loop to drop through, but I don't think these are supported by gcc, and they would certainly be very non-portable.
    There are several common ways to drop out of one or more outer loops. In many cases, there's nothing else in the loop following the switch so you can simply write
    switch (condition) {
    default:
    case 0:
    break;
    // other case statements here
    break;
    Else you can declare a loop control var and use the continue statement like this:
    for (i=0; i<jMax && !bDone; i++) {
    switch (condition) {
    default:
    case 0:
    bDone++; continue;
    // other case statements
    If you need to escape several loops and/or don't want to use loop control vars, you might consider structuring the code so you can use return to terminate the entire function. In the worst case of a very complex structure that you don't know how to simplify with a helper function, you can always resort to a goto:
    switch (condition) {
    default:
    case 0:
    goto escape;
    // other case statements here
    // remainder of code inside nested loops here
    escape: <first statement following the outermost loop>;
    Note that the statement following the escape label is always executed; i.e. when execution skips the goto it's as if the statement following escape was unlabeled. Use goto sparingly of course, since it's an artifact of unstructured programming. But when you really need a goto, it can make your code much easier to maintain.

  • Question about delete statement

    I have question about delete statement...
    i am performing some simple delete statement against one table..but its taking so long..How can we check whether particular delete statements actually deleting records or not..?

    Is the associated select-statement returning rows or not?
    If yes -> delete is deleting
    If no -> delete is just using CPU-cycles
    To tune the delete-statement, you have to tune the corresponding select-statement. To tune the select-statement, you want to read the thread When your query takes too long ...

  • Question about 'write' statement

    Hi,
    A question on write statement.
    I have a internal table itab which has field var. I am looping at this itab and writing horizontal heading output like below.
    example on the output heading:
    (3 spaces) itab-var (20 spaces) itab-var (20 spaces) itab-var.
    the coding is:
    loop at itab.
    write: 3 itab-var.
    endloop.
    I want to increase the space by 20 for every loop. How to increase this 3 by 20? Can we accomplish this way?
    Thank you for your time.

    hi krishen,
    just add 20 inside the loop , so that after every loop its value increases by 20
    for example:
    data: v  type i.
    v=3.
    do 3 times.
    write: at v(20).
    v=v+20.
    end do.
    hope it will help you
    regards
    Rahul sharma
    Edited by: RAHUL SHARMA on Sep 4, 2008 7:47 AM

  • Beginner question regarding switch statements with arrays....

    Doing a little project for my beginner's object oriented programming course. I've written the following code, but the switch statement won't recognize my array values....I'm required to use a switch statement in my program, which will count various character types in an external file....any insight is appreciated.
    import java.io.*;
    public class MyProg
      public static BufferedReader inFile;
      public static void main(String[] args)
        throws IOException, StringIndexOutOfBoundsException
        String line;
        inFile = new BufferedReader(new FileReader("TME5Part1.dat3"));
          char UpperCase[]= {'A','B','C','D','E','F','G','H','I','J','K','L','M',
                                          'N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};          
          char LowerCase[]=     {'a','b','c','d','e','f','g','h','i','j','k','l','m',
                                          'n','o','p','q','r','s','t','u','v','w','x','y','z'};
          char Digit[]= {'0','1','2','3','4','5','6','7','8','9'};
          char EndMark[]= {'!','.','?'};
          char MidMark[]= {',',':',';'};
        char symbol;                                                            
        int upperCaseCt = 0;                                             
        int lowerCaseCt = 0;
        int digitCt = 0;
        int endMarkCt = 0;
        int midMarkCt = 0;
          int spaceCt = 0;
          int otherCharCt = 0;
        line = inFile.readLine();          //read first line (priming read)
        while (line != null)               // Loop until end of data (empty line)
          for (int count = 0; count < line.length(); count++)  // Loop until end of line
            symbol = line.charAt(count);                    
                for (int i=0; i<=25;i++)                              
                        char uppercase=UpperCase;               //get array values for i
                        char lowercase=LowerCase[i];
                        if (i<=9) {char digit=Digit[i];}               
                        if (i<=2) {     char endmark=EndMark[i];     
                                            char midmark=MidMark[i];
                        switch(symbol)                                             
                                  case uppercase : upperCaseCt++;
                                            break;
                                  case lowercase : lowerCaseCt++;
                                                 break;
                                  case digit          : digitCt++;
                                                 break;
                                  case endmark     : endMarkCt++;
                                                 break;
                                  case midmark     : midMarkCt++;
                                                 break;
                                  case ' '          : spaceCt++;
                                                 break;
                                  default          : otherCharCt++;
                                                 break;
              line = inFile.readLine();                                   
         System.out.println("Number of uppercase letters = "+upperCaseCt);               
         System.out.println("Number of lowercase letters = "+lowerCaseCt);
         System.out.println("Nubmer of digits = "+digitCt);
         System.out.println("Number of end punctuation marks = "+endMarkCt);
         System.out.println("Number of mid punctuation marks = "+midMarkCt);
         System.out.println("Number of spaces = "+spaceCt);
         System.out.println("Number of other characters = "+otherCharCt);
    I was trying to do it this way rather than "case 'A':
    case 'B':
    case 'Z:" for each type of 'symbol'.
    Unfortunately, the switch statement is required or this would be easier with arrays and for loops...I'm not sure if my code is even possible. Thanks in advance =)
    Edited by: RiTarDid

    RiTarDid wrote:
    For sure it is the most straightforward way, but my curiosity is getting the better of me....I will most likely submit the program with the longer (value-by-value) switch method, as I haven't found anyone who can tell me how to properly reference an array value in a 'case'.Well, you can do this (basically):
    switch(some_array[some_index]) {
        case 'a':  blahblah
        case 'z':  blahblah
    }What you can't do is this:
    switch(some_scalar_value) {
      case a_whole_array:  blahblah
      case a_whole_another_array: blahblah
    }Because the latter isn't what "case" means.
    If you want to do something like the latter, use if/else statements. Here's a dirty little industry secret: people seldom use switch/case. if/else is a lot more common.
    Actually that dirty little secret isn't really particular dirty or particularly secret. It is, however, little.
    I just recall a suggestion to use arrays for any group that is more than 10 values in size;Well...sort of...
    You should use the expression of data that's appropriate for what the data is. If it's a collection of data of the same kind and an ordering, then an array or a java.util.List makes sense. If it's data that is of the same kind but no ordering and no duplicates are allowed, use a java.util.Set. (Etc. on this front.) If it's a collection of un-alike data, but which belongs in associated groups (e.g., a user's name, age, height, and whether s/he's married) then you should create a class that represents that logical grouping. Etc. If you have more than 10 individual data that can't be grouped or collected somehow, then chances are you need to rethink what's happening.
    so I wanted to see if an array could be employed for comparisons with the 'switch' statement. The program is simple enough, I'm just trying to flex my problem-solving muscle in different ways. :)
    thanks for replying, hope I can get a definite "yes, it can be done this way" or "no it can't" if there's anyone out there who knows.....The problem is that your example is contrived. So you can do a variety of things that fit into the contrivance, but they'd be weird things.
    In practice, you'd want to use the character classification methods in Character, if you wanted to characterize a bunch of characters. Or maybe a regular expression. There's no need to keep an array of characters to match against if you want to determine whether a particular character is upper case. In fact, that's the wrong way of doing things, because Character.isUpperCase is more likely to tell whether any character (not just stuff that's also an element of ASCII) qualifies as upper case.

  • Beginner question about prepared statements...PLEASE help! :-)

    First let me say thanks for the assistance. This is probably really easy to do, but I'm new to JSP and can't seem to figure it out.
    I want to dynamically populate a table that shows whether a particular person has an appointment at a given date and time with a user. To do this, I want to query the MySQL database for the lastname of the person with the appointment that occurs with the user at the year, month, date, and time, in question.
    THE CODE BELOW DOESN'T WORK (obviously) BUT SOMEWHAT ILLUSTRATES WHAT I'M TRYING TO ACCOMPLISH:
    <%
    Driver DriverTestRecordSet = (Driver)Class.forName(MM_website_DRIVER).newInstance();
    Connection ConnTestRecordSet = DriverManager.getConnection(MM_website_STRING,MM_website_USERNAME,MM_website_PASSWORD);
    PreparedStatement StatementTestRecordSet = ConnTestRecordSet.prepareStatement("SELECT lastname FROM appts_pid1 WHERE user_id='<%=(((Recordset1_data = Recordset1.getObject(user_id))==null || Recordset1.wasNull())?"":Recordset1_data)%>' AND year='<%= yy %>' AND month='<%= months[mm] %>' AND date='<%= dates[dd] %>' AND appttime='16:15:00'");
    ResultSet TestRecordSet = StatementTestRecordSet.executeQuery();
    boolean TestRecordSet_isEmpty = !TestRecordSet.next();
    boolean TestRecordSet_hasData = !TestRecordSet_isEmpty;
    Object TestRecordSet_data;
    int TestRecordSet_numRows = 0;
    %>
    The real problem comes in the prepared statement portion. If I build the prepared statement with static values like below, EVERYTHING WORKS GREAT:
    PreparedStatement StatementTestRecordSet = ConnTestRecordSet.prepareStatement("SELECT lastname FROM appts_pid1 WHERE user_id='1' AND year='2002' AND month='October' AND date='31' AND appttime='16:15:00'");
    But when I try to use dynamic values, everything falls apart. It's not that the values aren't defined, I use the user_id, year <%= yy %>, month <%= months[mm] %>, etc. elsewhere on the page with no problems. It's just that I can't figure out how to use these dynamic values within the prepared statement.
    Thanks for reading this far and thanks in advance for the help!!!!

    Hi PhineasGage
    You are little bit wrong in your
    your preparedStatement.
    Expression tag within scriptlet tag is invalid.
    Whenever you are appending the statement with
    expression tag, append it with "+" and remove
    expression tag.
    Hopefully it will work
    ThanksThanks for the response!
    I know that the expression tag within scriptlet tag is invalid. I just need a workaround for what I want to do.
    I'm unclear what you mean by "Whenever you are appending the statement with expression tag, append it with a "+" and remove expression tag".
    Could you give an example?
    In the meantime, I've been trying to digest the docs on prepared statements and have changed the code to look like:
    PreparedStatement StatementTestRecordSet = ConnTestRecordSet.prepareStatement("SELECT lastname FROM appts_pid1 WHERE user_id= ? AND year= ? AND month= ? AND date= ? AND appttime='13:15:00'");
    StatementTestRecordSet.setInt(1,1);
    StatementTestRecordSet.setInt(2,2002);
    StatementTestRecordSet.setString(3,"October");
    StatementTestRecordSet.setInt(4,31);
    Again, WITH THE STATIC VALUES, THIS WORKS FINE...but when I try to use expressions or variables like below, things don't work:
    StatementTestRecordSet.setInt(2,<%= yy %>);
    Obviously, I'm doing something wrong, but there has to be a way to use variables within the prepared statement.
    ALSO, the values are being passed to this page via URL in the form:
    samplepage?user_id=1&year=2002&month=October&date=31
    Based upon this information, is there another way (outside of stored procedures in the db) to do what I want to do? I'm open to ideas.

  • A question About SUBMIT statement

    Hi,
    By SUBMIT statement, i can trigger another report. If the called report runs into dump, how can i detech/catch the dump in the calling report? I tested. It seems impossible to catch the dump. The calling report will also dump.
    My question is, if the called report runs into dump, how to detect the dump and avoid dump in calling report?
    Thanks in advance,
    Best Regards, Johnney.

    hi
    you can catch this kind of error or exeption from the respective report
    then pass this error or exeception to the calling report
    go through the  example I  am giving , ti have done it like this only  
    SUBMIT zgurep03 AND RETURN WITH SELECTION-TABLE li_seltab .
    then in the called reprot
    *Check ledger
      SELECT SINGLE * FROM t881 WHERE rldnr = p_rldnr.
      IF sy-subrc NE 0.
        SET CURSOR FIELD 'P_RLDNR'.
         MESSAGE e448 WITH p_rldnr
          MESSAGE e446 INTO lv_text .
          lv_type = 'E'.
    Capturing the error messages.
    EXPORT lv_text TO MEMORY ID 'TX'(004).
    EXPORT lv_type TO MEMORY ID 'TP'(005).
    in calling report
      IMPORT gv_type1 TO gv_type FROM MEMORY  ID 'TP'.
      IMPORT gv_text1 TO gv_text FROM MEMORY ID 'TX'.
    preparing error message in the callge report for the calling report
    PERFORM prepare_message
            USING sy-msgid
                  lv_msgno
                  lv_msgv1
                  lv_msgv2
                  lv_msgv3
                  lv_msgv4
            CHANGING gv_text.
    preparing  error message
    FORM prepare_message  USING    p_sy_msgid
                                   p_sy_msgno
                                   p_sy_msgv1
                                   p_sy_msgv2
                                   p_sy_msgv3
                                   p_sy_msgv4
                          CHANGING p_gv_text.
      CALL FUNCTION 'FORMAT_MESSAGE'
        EXPORTING
          id        = p_sy_msgid
          lang      = 'EN'
          no        = p_sy_msgno
          v1        = p_sy_msgv1
          v2        = p_sy_msgv2
          v3        = p_sy_msgv3
          v4        = p_sy_msgv4
        IMPORTING
          msg       = gv_text
        EXCEPTIONS
          not_found = 1
          OTHERS    = 2.
      IF sy-subrc <> 0.
        MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
                WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
      ENDIF.
    I guess this will solve your problem
    Regards
    Prashant

  • Question about call statement in trigger

    I faced a question in written exam.
    A CALL statement inside a trigger allow us to call
    a)package
    b)procedure
    c)function
    d)another trigger
    Can anyone give me answer with reason?
    I used CALL statement inside trigger but not allowing to use it. Might be earlier in oracle CALL statement we can use..its only a guess so I am asking in forum..
    plz guide me..
    rgds,
    pc

    You can use CALL in a trigger without resorting to EXECUTE IMMEDIATE
    SQL> create table t1 (
      2    col1 number
      3  );
    Table created.
    SQL> create procedure t1_proc
      2  as
      3  begin
      4    dbms_output.put_line( 'In T1_PROC' );
      5  end;
      6  /
    Procedure created.
    SQL> ed
    Wrote file afiedt.buf
      1  create trigger trg_t1
      2    before insert on t1
      3    for each row
      4* call t1_proc
      5  /
    Trigger created.
    SQL> set serveroutput on;
    SQL> insert into t1 values( 1 );
    In T1_PROC
    1 row created.I can't think of any reason that you'd actually intentionally structure your code this way in this day and age because it would be rather likely to cause confusion for whoever had to support this in the future. But it is valid syntax that probably made sense back in Oracle 5.
    Justin

  • Question about sql statement

    Hi expert,
    I have following sql statement, function 'hiroc_get_delta_amount1' and 'hiroc_get_delta_amount2' are separately used in select and where subclause. these two function are exactly same, except that there is a inserting log statement inside. for function 'hiroc_get_delta_amount1' , logs are supposed to write into log table1, whereas for function 'hiroc_get_delta_amount2' , logs are supposed to write into log table2. after running this sql, I got data loaded into log table2, however, there is no data loaded into log table1.
    could you please tell me why there is no data in log table2 for function
    1. sql statement;
    select
    pp.policy_premium_pk,
    pp.policy_fk,
    pp.policy_term_fk,
    pp.risk_fk,
    pp.coverage_fk,
    pp.transaction_log_fk,
    pp.coverage_component_code,
    hiroc_rpt_user.hiroc_get_delta_amount1(pp.policy_fk, pp.policy_term_fk, pp.risk_fk, pp.coverage_fk, pp.transaction_log_fk, pp.coverage_component_code),
    pp.rate_period_from_date
    from PRODBKUPDW_MART.rmv_policy_premium pp
    where pp.rate_period_type_code = 'TERM_COVG'
    and pp.coverage_component_code 'NETPREM'
    and hiroc_rpt_user.hiroc_get_delta_amount2(pp.policy_fk, pp.policy_term_fk, pp.risk_fk, pp.coverage_fk, pp.transaction_log_fk, pp.coverage_component_code) != 0
    group by pp.policy_premium_pk,
    pp.policy_premium_pk,
    pp.policy_fk,
    pp.policy_term_fk,
    pp.risk_fk,
    pp.coverage_fk,
    pp.transaction_log_fk,
    pp.coverage_component_code,
    pp.rate_period_from_date;
    2. log inserting statement used for both functions:
    (1) function 'hiroc_get_delta_amount1'
    insert into HIROC_RPT_USER.LOG_TEST1 values (v_start, sysdate,
    p_policy_fk,p_policy_term_history_fk,p_risk_fk,p_coverage_fk,p_transaction_log_fk,p_comp_code);
    COMMIT;
    (2) function 'HIROC_GET_DELTA_AMOUNT_1'
    insert into HIROC_RPT_USER.LOG_ZB_TEST_1 values (v_start, sysdate,
    p_policy_fk,p_policy_term_history_fk,p_risk_fk,p_coverage_fk,p_transaction_log_fk,p_comp_code);
    COMMIT;

    Are your functions using autonomous transactions?
    We also need more information about the log tables etc. as we cannot tell what the problem would be from just that query, and no data.

  • Question about some statement

    Hello Gurus,
           as for a statement "The MBW job BI_BTCH__FX_PAYMENT_DATA=X10M and itu2019s child job ended with completed Abnormally status.", I have some question as follows:
         (1) where does they check out this job " BI_BTCH__FX_PAYMENT_DATA=X10M " ?  what do that "="  and "X10M" and "BI_BTCH__FX_PAYMENT_DATA"   mean ?
        (2) how does " MBW job BI_BTCH__FX_PAYMENT_DATA=X10M "  match some BW object?
        (3) what is  itu2019s child job ?
    Ma

    Is the associated select-statement returning rows or not?
    If yes -> delete is deleting
    If no -> delete is just using CPU-cycles
    To tune the delete-statement, you have to tune the corresponding select-statement. To tune the select-statement, you want to read the thread When your query takes too long ...

  • Question about Merge Statement

    Is it possible to use a CASE statement inside the update clause of a merge statement? Also what about a function?
    I have a string (In Source) that needs to be split into multiple columns (In Target) depending on values in other columns (In Source).
    I am on 11iR1

    Hi Chris,
    You can take a look at the below examples :
    SQL>create table t_test
    col1,col2,col3
    ) as
    select 1,2,3 from dual union all
    select 2,3,4 from dual union all
    select 3,4,2 from dual union all
    select 9,10,12 from dual union all
    select 11,23,43 from dual
    create table succeeded.
    SQL>select * from t_test;
    COL1                   COL2                   COL3                  
    1                      2                      3                     
    2                      3                      4                     
    3                      4                      2                     
    9                      10                     12                    
    11                     23                     43    
    SQL>merge INTO t_test t_t USING
      SELECT
        1 AS col1
      FROM
        dual
    ) d_d
    ON
    (d_d.col1 = t_t.col1)
    WHEN matched THEN
      UPDATE set
        col2 = (
          CASE
            WHEN d_d.col1 = 1
            THEN 123
            ELSE -1
          END );
    1 rows merged
    SQL>select * from t_test;
    COL1                   COL2                   COL3                  
    1                      123                    3                     
    2                      3                      4                     
    3                      4                      2                     
    9                      10                     12                    
    11                     23                     43                    

  • Question about switching from pc to mac

    I am going to be purchasing a new computer in March. I am seriously considering switching to a mac. I've owned a mac before and I obviously have my reasons for wanting to go back...however...I've always been a pc and all of my software is pc based...and a lot of them I no longer have the install discs for. I'm a designer and my main concern is losing the ability to use my software, such as Adobe CS4 because I dont' know if it will be compatible with the mac. My question is, is there a way to transfer my software from my pc to a mac without any external hard drives and without having to buy all new software for the new mac? This is going to be the deciding factor on whether or not I go with a mac instead of a new pc. I really could use some input on this. Thanks so much.

    If you've bought your Mac, be sure to exchange your Windows CS4 license before CS5 comes out. Adobe will only do a cross-platform swap on the current version (which I found out the hard way!)
    Take a look here: http://kb2.adobe.com/cps/405/kb405819.html
    I have heard of a lot of folks having trouble getting a cross-platform swap. Also, don't believe anything an Adobe customer support rep tells you. They are either "misinformed" or they flat-out lie.
    Best of luck!

  • Question about conversational state of Stateless bean....

    Hello all,
    I have a simple stateless bean which parses an XML file and stores the xml content as an list of 2-D arrays in member variables. Here is quick look at design...
    import javax.ejb.Stateless;
    // included other libraries
    import java.util.List;
    import java.util.ArrayList;
    @Stateless
    public class XMLParseBean implements XMLParseBeanInterface {
        public List<String> strParameters;
        public List<String> getStrParameters() {
            return strParameters;
        private void setStrParameters(List<String> strParameters) {
            this.strParameters = strParameters;
        public void parseXML(String strFileName) {
               /* Open the XML file and do initializations for xml parsing here
                setStrParameters(visitNode(doc.getDocumentElement()));
        private List<String> visitNode(Element thisNode) {
                /* Parse the XML here */
                return strNodes; // return the node names and their values
    }My question is : if I inject this bean in another bean, call the method for parsing XML and then call the getParameter method to access the value of member variable, will it work.
    I mean since I am using stateless bean, does the conversation state end when the parseXML method ends?

    sir_edward wrote:
    Hi vikram8jp,
    The session of an stateless bean ends after a method call. If you call a method of your bean, the bean will forget all attributes when the method ends. If you want to save attributes, you have to use a stateful bean.
    Regards
    Sir EdwardHello Sir Edward,
    That answers my query.

  • Question about switching DPS accounts and In-App Purchases

    Here comes a tricky one
    I have my app published on Apple using an specific DPS account (aka [email protected]) and I have some in-app purchases into the app that the final users have already bought.
    For some reason, I need to switch the app to use a different DPS account (let's say  [email protected]) and I need to recompile the app and make it available on App Store (Apple Account will be the same one). Concerning the folios, I can upload them again with the same product ID as the older ones and delete the older folios from the older account.
    Question is:  What would happen to my In-App Purchases? Will I be able to restore my purchases if I have a new app with a different account? Will Adobe allow to use the same Product ID for another folio even if it was used previously?
    Hope you can help me out with this.

    Phone is now fixed and because the game was saved to my game centre, it loaded with all purchases. So I'm thinking that as long as the game is saved to game centre, it will reload as it was previously.

  • Hi Experts, a question about Account statement(sapscript)?

    Hi Experts,
    I am working on Account statement, I want to know what is the field for opening balance on the first date of the month, I have a structure(RF140) to use and I found there is final balance(rf140-datu2, rf140-saldo) used in the form, can anyone tell me what is opening balance and final balance? what are the corresponding fields? thank you in advance, thanks.
    Kind regards
    Dawson
    Edited by: dawson wang on Jun 22, 2009 7:00 AM

    Hi,
    U can go to SE11 & give structure name RF140 & press display button. it displays all the fields in struture...
    FYI...field name for Open balance is 'OPBETRAG' & for Final Balance is 'GSALDD'.
    Hope it helps!!
    Rgds,
    Pavan

Maybe you are looking for