How to use Constants in Switch statements?

Hello all,
The following code snippet gives error, please give me guidance.
========
static Object tokenize(StreamTokenizer st)
throws NumberFormatException, IOException {
Object token = null;
try {
if (st.nextToken() == st.TT_EOF) {
throw new EOFException();
} catch (IOException e) {
throw e;
switch(st.ttype) {
case st.TT_NUMBER:
token = new Double(st.nval);
break;
case st.TT_WORD:
token = st.sval;
break;
case st.TT_EOL:
throw new NumberFormatException();
default:
throw new NumberFormatException();
return token;
=================
regards.

Perhaps it wants you to do "StreamTokenizer.TT_WORD" rather than "st.TT_WORD".
Why catch IOException, just to throw it again?

Similar Messages

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

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

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

  • How to use Double selection If statements?

    Ok, this is what I have to do:
    Present a menu to the user from which there will be 6 choices, A = add three number, S = subtract 2 numbers, M = multiply three numbers, D = divide two numbers, O = modulus two numbers, E = Exit.
    2) If the user enters an A,S,M,O,D the program will prompt the user for numbers and perform the needed math on them.
    3) if the user enters an E then the program will thank the user, and exit.
    4)the program HAS to use Double Selection If Statements (no idea how to do these)
    5) the program should use float point numbers for all the numbers entered, besides modulus.
    heres what i have so far.. -_-
    import javax.swing.JOptionPane;
    public class Ifprogram
    public static void main (String[] args)
      String Intro;
      String A;
      String S;
      String M;
      String D;
      String O;
      String Exit;
      Intro = JOptionPane.showInputDialog(null, "Enter A to add 3 numbers \n S to Subtract two numbers \n M to Multiply three numbers \n D to Divide two numbers \n O to Modulus two numbers \n and E to Exit.");
       A = JOptionPane.showInputDialog(null, "You selected to add 3 numbers. Enter the first digit to add.");
       S = JOptionPane.showInputDialog(null, "You selected to substract two numbers. Enter the first digit to subtract.");
    }IM SO LOST.
    If anyone could give me some tips on what to do, or where to get, that'd help A LOT! Thank you.

    I can see that working, but
    if(user entered 'A') {
                        A = JOptionPane.showInputDialog(null, "You selected to add 3 numbers. Enter the first digit to add.");
                    } else if(user entered 'S') {
                       S = JOptionPane.showInputDialog(null, "You selected to substract two numbers. Enter the first digit to subtract.");
                   }Is not working..
    The errors i get:
    16 ')' expected
                   if(user entered 'A') {
                                    ^
    21: illegal start of expression
                    ^
    2 errors
    Tool completed with exit code 1Edited by: JackJ11 on Mar 16, 2010 4:29 PM

  • How to use INSERT INTO ALL statement in jdbc prepared statement with beans

    Kindly give me some example that how we can use "INSERT INTO ALL STATEMENT" in jdbc prepared statement inside a jsf bean?
    Actually i want to take employee id's of present employees using single jsf page and using one textbox for each employee id.
    How can i use INSERT INTO ALL statement to achieve this?
    Following is my code snippet.
    AttendanceBean.java:
    public class AttendanceBean {
    private int atteid;
    private String attdname;
    private int attday;
    private int attmonth;
    private int attyear;
    public static Connection getAttConnection() throws Exception {
    String driver = "oracle.jdbc.driver.OracleDriver";
    String url = "jdbc:oracle:thin:@localhost:1521:globldb3";
    String username = "scott";
    String password = "tiger";
    Class.forName(driver);
    Connection conn = DriverManager.getConnection(url, username, password);
    return conn;
    public String addAttendance(){
    Connection conn = null;
    PreparedStatement pstmt = null;
    boolean committed = false;
    try {
    conn = getAttConnection();
    conn.setAutoCommit(false);
    String query = "INSERT ALL INTO attendance VALUES (?,?,?,?,?)";
    pstmt = conn.prepareStatement(query);
    pstmt.setInt(1,this.atteid);
    pstmt.setString(2,this.attdname);
    pstmt.setInt(3,this.attday);
    pstmt.setInt(4,this.attmonth);
    pstmt.setInt(5,this.attyear);
    pstmt.executeUpdate();
    conn.commit();
    conn.setAutoCommit(true);
    committed = true;
    return "home.xhtml";
    } catch (Exception e) {
    e.printStackTrace();
    return "CRM.xhtml";
    } finally {
    try{
    if (!committed) conn.rollback();
    if (pstmt != null) pstmt.close();
    if (conn != null) conn.close();
    }catch(Exception e){
    e.printStackTrace();
    }

    Check this program for some info on Push buttons:
    1-DEMO_DYNPRO_PUSH_BUTTON
    2-DEMO_DYNPRO_MODULE
    3-DEMO_DYNPRO_ON_CONDITION
    Suppose Your screen is 101
    Then in that screen create one push button and assign it a function code.
    Now in the PAI of the 101 screen
    Create Module for user command
    Inside that module checc the sy-ucomm if sy-ucomm eq <Function code of your push button>
    Insert the values in database.
    *& Module USER_COMMAND_0101 INPUT
    process after input for screen 0101 *
    MODULE USER_COMMAND_0101 INPUT.
    CASE OK_CODE.
    WHEN 'SAVE'.
    *Insert the values here
    WHEN 'DISP'.
    ENDCASE.
    CLEAR OK_CODE.
    ENDMODULE. " USER_COMMAND_0101 INPUT
    Regards
    Neha
    Edited by: Neha Shukla on Dec 3, 2008 1:02 AM
    Edited by: Neha Shukla on Dec 3, 2008 1:02 AM
    Edited by: Neha Shukla on Dec 3, 2008 1:06 AM

  • How to use a KVM switch with my IMAC

    Have a new IMAC and wanting to use my KVM switch - is there a way to use it?
    Thanks,

    Zimmer1956 wrote:
    Have a new IMAC and wanting to use my KVM switch - is there a way to use it?
    If you mean you want to send video from another computer to the iMac display,
    the answer is: NO WAY. iMacs have no video input; the mini-DVI is output-only.
    If you want to send iMac video to a shared external monitor, it might work -- if
    you can find a KVM switch for a USB keyboard & mouse.
    Looby

  • How to use a KVM switch with a Pavillion 23

    I have a Pavillion 23, and it has no VGA port, but it does have a USB port.
    I have another machine that is not an all in one pc, and I was hoping to use a KVM switch to use the Pavillion 23's video monitor capabilites, and just toggle between it and my other machine. I have a USB to VGA converter. Can this work? Will this create some sort of infinate loop? I have a sneaking suspicion that I need a 2nd usb to VGA converter. Am I right?

    Hi,
    This will be the out port, not in port therefore you can't use the 23" monitor.
    Regards.
    BH
    **Click the KUDOS thumb up on the left to say 'Thanks'**
    Make it easier for other people to find solutions by marking a Reply 'Accept as Solution' if it solves your problem.

  • Using CONSTANT in Condition Statement

    Hi
    What I am trying to do is put CONSTANT into IN Condition Statement.
    When I use Bind variables just like :bind, It works properly
    But What if I use as a CONTANT, It doesn't work.
    In my opinion, parenthesis is not work well.
    Please help me out
    thanks in advance and below is PL/SQL CODE
    PROCEDURE PROC_MAIN
    iUserID          IN     VARCHAR2,
    iJobID IN VARCHAR2
    ) AS
    C_AGENT CONSTANT VARCHAR(20) := '10,11';
    C_staff CONSTANT VARCHAR(20) := '40';
    C_newStaff CONSTANT VARCHAR(20) := '50';
    C_ETC CONSTANT VARCHAR(20) := '20,30';
    BEGIN
    vJobId :=
    CASE iJobID
    WHEN '41' THEN C_AGENT
    WHEN '42' THEN C_staff
    WHEN '43' THEN C_newStaff
    WHEN '40' THEN C_ETC
    END;
    insert into tbl_monthly
    (emp_no, salary)
    select emp_no, salary from tbl_emp
    where Staff_cat in vJobId ;
    end;
    Message was edited by:
    allbory

    Hi,
    Please check the changes:
    Note: table_name is changed to test.
    CREATE OR REPLACE PROCEDURE PROC_MAIN
    iUserID IN VARCHAR2,
    iJobID IN VARCHAR2
    ) AS
    C_AGENT CONSTANT VARCHAR(20) := '10,11';
    C_staff CONSTANT VARCHAR(20) := '40';
    C_newStaff CONSTANT VARCHAR(20) := '50';
    C_ETC CONSTANT VARCHAR(20) := '20,30';
    vJobId          VARCHAR2(20);BEGIN
    vJobId :=
    CASE iJobID
    WHEN '41' THEN C_AGENT
    WHEN '42' THEN C_staff
    WHEN '43' THEN C_newStaff
    WHEN '40' THEN C_ETC
    END;
    EXECUTE IMMEDIATE 'INSERT INTO tbl_monthly(empno, salary) SELECT empno, sal FROM scott.emp WHERE deptno IN ('||vJobId||')' ;
    END;

  • How to use settings with a state machine?

    I have a "classic" data acquisition program that acquires voltages from different sensors. Each DAQ read subvi has some settings for the scale, range of voltage etc.; additionally I have set a certain buffer size, sampling rate etc.
    I would like to show on the front panel only the start, stop type of buttons, file name and charts, and 'hide' the settings in a subvi. I already built the subvi but now the problem is how to hide it and how to call it through a "settings" button whenever I want to change something. I tried this using New events handler (using events in a while loop); the problem is when I start the program, the settings in the application do not take the settings in the subvi, they all go to 0 (I used shift registers). I started to wonder if this is a good approach or what could I do to make the settings available right from the start.
    Did anybody have the same problems and could give me some suggestions and an example?
    Thank you. 

    Hello,
    Attached is an example to help you get started.  The popup VI in the event structure is called and shows it's front panel when called because of the subVI node setup (right click to check this) - the instance of the subVI outside the loop, which initializes the shift register, does not pop up because it's subVI node setup is not set that way. 
    If you run the example and study the code, you'll find comments in the code to help you understand the behavior.
    I hope this helps!
    Best Regards,
    JLS
    Best,
    JLS
    Sixclear
    Attachments:
    Change Settings Example.llb ‏46 KB

  • How to use REGEXP for case statement

    Hello everyone, I'm very new here and am struggling with a using REGEXP in a case statement, OK I am using the REGEXP to find all strings that match a specific format for a particular brand of product, for example serial numbers, and I need to be able to say something like [case when(xx.brandid) = '123' then if xx.serialnumber REGEXP_LIKE(xx.serialnumber,'[A-za-z][A-za-z][A-za-z]\d{5,}[A-za-z]$') then 'TRUE' else 'FALSE' end "TRUE/FALSE".]
    Help would be greatly appreciated with this as I feel like I'm going backwards trying to figure this out
    Thanks in advance for any assistance.

    Like this?
    case
       when xx.brandid = '123' and
            regexp_like(xx.serialnumber,'[A-za-z][A-za-z][A-za-z]\d{5,}[A-za-z]$') then
          'TRUE'
       else
          'FALSE'
    end

  • How to use constant in expression language

    I have class Constant which contains
    public static final (constant fields).
    I want to use those constants in expression language in jsp
    ${requestScope.result eq with some constant}
    <c:if test="${requestScope.result eq '<%= Constants.MODE %>'}">
                   Hello World
              </c:if>     
    It does not print Hello World
    even though MODE is 'hello' and result is also set to 'hello'.
    Message was edited by:
    mihir_kapadia

    Its not that simple. There is an article in [url http://www.javaranch.com/journal/200601/Journal200601.jsp#a3]javaranch  about the usage of constants in EL.
    There is [url http://forum.java.sun.com/thread.jspa?forumID=45&threadID=508847]this  cool code snippet from forum user evnafets that would help you with your problem.
    ram.

  • How to use on/off switch with the cover on?

    Ive only just got my IPAD so it may well be me but why is the on/off switch 'under' the cover.  Surely, I dont have to take the cover off everytime I want to switch it on and off?  Or should I not switch it on and off and just use the cover to put in 'standby' mode?

    Unless you will not be using the iPad for a long time, you do not need to switch it OFF, just use the magic cover to put it to sleep (standby).
    BTW, the ON/OFF switch is at the top, not the Home button at front.
    Message was edited by: ckuan

  • How can use iphone 4g in states with gsm?

    i live in iran.i cant use my iphone 4g in iran.what can i do?please help me.

    The iPhone is sold in the U.S. as carrier locked with AT&T. Return it to whoever you purchased it from and get your money back.

  • How to use a table name in the select statement using a variable?

    Hi Everybody,
                       I got a internal table which has a field or a variable that gets me some tables names. Now I need to retrieve the data from all these tables in that field dynamically at runtime. So could you suggest me a way out to use the select query which uses this variable as a table ?
    Regards,
    Mallik.

    Hi all,
    Actually i need some more clarification. How to use the same select statement, if i've to use the tabname in the where clause too?
    for ex : select * from (tab_name) where....?
    Can we do inner join on such select statements? If so how?
    Thanks & Regards,
    Mallik.

  • Having problem with switch statement..please help

    here my question :
    GUI-based Pay Calculator
    A company pays its employees as executives (who receive a fixed weekly salary) and hourly workers (who receive a fixed hourly salary for the first 40 hours they work in a week, and 1.5 times their hourly wage for overtime worked).
    Each category of employee has its own paycode :
    ?     Paycode 1 for executives
    ?     Paycode 2 for hourly workers
    Write a GUI-based application to compute the weekly pay for each employee. Use switch to compute each employee?s pay based on that employee?s paycode.
    Use CardLayout layout manager to display appropriate GUI components. Obtain the employee name, employee paycode and other necessary facts from the user to calculate the employee?s pay based on the employee paycode:
    ?     For paycode 1, obtain the weekly salary.
    ?     For paycode 2, obtain the hourly salary and the number of hours worked.
    You may obtain other information which you think is necessary from the user.
    Use suitable classes for the GUI elements. (You can use javax.swing package or java.awt package for the GUI elements.)
    here my code so far :
    import java.awt.;*
    import java.awt.event.;*
    import javax.swing.;*
    *public class PayrollSystem implements ItemListener {*
    JPanel cards, JTextField, textField1, JLabel, label1;
    final static String EXECUTIVEPANEL = "1.EXECUTIVE";
    final static String HOURLYPANEL = "2.HOURLY WORKER";
    public void addComponentToPane(Container pane)
    *//Put the JComboBox in a JPanel to get a nicer look.*
    JPanel comboBoxPane = new JPanel(); //use FlowLayout
    JPanel userNameAndPasswordPane = new JPanel();
    *// User Name JLabel and JTextField*
    userNameAndPasswordPane.add(new JLabel("NAME"));
    JTextField textField1 = new JTextField(25);
    userNameAndPasswordPane.add(textField1);
    *String comboBoxItems[] = { EXECUTIVEPANEL, HOURLYPANEL };*
    JComboBox cb = new JComboBox(comboBoxItems);
    cb.setEditable(false);
    cb.addItemListener(this);
    comboBoxPane.add(cb);
    *//Create the "cards".*
    JPanel card1 = new JPanel();
    card1.add(new JLabel("WEEKLY SALARY"));
    card1.add(new JTextField(6));
    card1.add(new JLabel("TOTAL PAY"));
    card1.add(new JTextField(8));
    card1.add(new JButton("CALCULATE"));
    JPanel card2 = new JPanel();
    card2.add(new JLabel("HOURLY SALARY"));
    card2.add(new JTextField(6));
    card2.add(new JLabel("TOTAL HOURS WORK"));
    card2.add(new JTextField(8));
    card2.add(new JButton("CALCULATE"));
    *//Create the panel that contains the "cards".*
    cards= new JPanel(new CardLayout());
    cards.add(card1, EXECUTIVEPANEL);
    cards.add(card2, HOURLYPANEL);
    pane.add(comboBoxPane, BorderLayout.PAGE_START);
    pane.add(userNameAndPasswordPane, BorderLayout.CENTER);
    pane.add(cards, BorderLayout.PAGE_END);
    public void itemStateChanged(ItemEvent evt)
    CardLayout cl = (CardLayout)(cards.getLayout());
    cl.show(cards, (String)evt.getItem());
    ** GUI created*
    *private static void createAndShowGUI() {*
    *//Make sure we have nice window decorations.*
    JFrame.setDefaultLookAndFeelDecorated(true);
    *//Create and set up the window.*
    JFrame frame = new JFrame("GUI PAY CALCULATOR");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    *//Create and set up the content pane.*
    PayrollSystem demo = new PayrollSystem();
    demo.addComponentToPane(frame.getContentPane());
    *//Display the window.*
    frame.pack();
    frame.setVisible(true);
    *public static void main(String[] args) {*
    *//Schedule a job for the event-dispatching thread:*
    *//creating and showing this application's GUI.*
    *javax.swing.SwingUtilities.invokeLater(new Runnable() {*
    *public void run() {*
    createAndShowGUI();
    HOW CAN I PERFORM THE SWITCH STATEMENT INSIDE THIS CODE TO LET IT FULLY FUNCTIONAL..?
    I MUST PERFORM THE SWITCH STATEMENT LIKE IN THE QUESTION..
    PLEASE HELP ME..REALLY APPRECIATED...TQ

    hi
    A switch works with the byte, short, char, and int primitive data types. So you can simply give the
    switch (month) {
                case 1: 
                            System.out.println("January");
                            break;
                case 2:  {
                            System.out.println("February");
                             break;
                case 3: {
                              System.out.println("March");
                              break;
                             }where month controlls the flow
    moreover u can go to http://www.java-samples.com/java/free_calculator_application_in_java.htm
    for reference, just replace the if statement with switch with correct syntax

  • I need some advice on switch statements

    I need to make an applet that accepts 2 things: a product # and how many of a product someone is buying. I have to display the total cost of a product and all the products bought together. My code so far is this:
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    public class store extends Applet implements Actionlistener
         Float runningTotal, overallTotal, howmany;
         TextField txtproductnumber, txthowmany;
         Label lblproductnumber, lblhowmany
         Public void init ()
              lblproductnumber = new Label("Product number:");
              txtproductnumber = new TextField(2);
              add (lblproductnumber);
              add (txtproductnumber);
              lblhowmany = new Label("How many:");
              txthowmany = new TextField(2);
              txthowmany.addActionListener(this);
              add (lblhowmany);
              add (txthowmany);
         public void paint (Graphics g)
              g.drawString ("The total for this purchase is $" + runningtotal, 40, 120);
              g.drawString ("The total for all purchases this session is $" + overalltotal, 40, 140);     
         public void actionPerformed(ActionEvent e)
              productnumber      = Float.valueOf(txtproductnumber.getText());     
              howmany      = Float.valueOf(txthowmany.getText());
         public static void main(string args[])
              switch(runningTotal)
                   Case 1:
                   Case 2:               
                   Case 3:
                   Case 4:
                   Case 5:
    }I got to this point and just froze on what to do next, I'm not even sure if this is going in the right direction... any help appreciated and I have 15 duke dollars assigned to be handed out amongst those who help.
    Thanks!

    Or you can create an int variable say option. Then use an if statement to determine the value of option. Then you can use option in switch statement.
    for example
        if(args[0]=="abcd")
           option=1;
        else
           option=2;
        switch(option){
            case 1:
            case 2:
        }

Maybe you are looking for

  • How can I create a new page???

    I do a new actionRouter("jsp"); and it do well but I want to have this page in a new page, no in the same one. Somebody can help me?? thank you

  • TS4002 How can I get a notification sound when an email arrives?

    I am using Safari and icloud to manage and check emial. I am not receiving a notification sound. How can I get an audiable sound to alret me?

  • Internal and external DVD burner ?

    Hi all, have a general question, currently have a HP ProBook 6455b, obviously has an internal DVD burner.. I am looking to add an external DVD burner...is this possible to run an internal and external at the same time? would I need additional burning

  • Standby Databse Log Problem

    Hi, i am trying to Configure Data Guard in two server. I have followed all the requisite steps in Primary Database and then copied the same to Standby to run adcfgclone.pl in the standby.Then i have updated the pfile in Standby,checked that archieve

  • Error when doing material transfer

    hi expert, when doing material transfer from plant 0001 to plant 0002, error pops up : "maintain vendor for the customer 1234 attached to supplying plant 1234".. what should i do?? thanks