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.

Similar Messages

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

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

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

  • Multiple rawValues and switch statements - can you do this?

    Hi, a simple question (i hope)
    first i have to use javascript for his one....
    Im just starting a form and it will have about a dozen dropdown lists (over about 15 pages), each with quite a few variables (i feel a headache coming on already...)
    and what i would like to be able to do is have text fields at the end of the form (hidden) and insert data into them depending on what combination of choices the user has made in some or all of the dropdown lists.
    I know how to get a standard switch statement to work fine but can you (and if so what is the syntax like) do this with multiple lists - and what event would be best to link it to - calculate perhaps?
    the switch would be using stored variables and user entered data to produce composite output to the text field (so case: listA.rawvalue = 1 and listB.rawvalue = nine, and listC.rawvalue = cat etc etc [then] this.rawvalue = v1.value + listB.rawvalue etc.....
    I'm sure you get the issue im struggling with  - I've tried it a few ways but my syntax must be off somewhere
    can anyone assist with the syntax for this kind of thing --or a sample would be fantastic.
    cheers

    Hey Legallogic!
    I'm not 100% certain I understand what you are struggling with but I'd be happy to help.  If you could provide an alternate explanation of your issue I'll take a look and help you solve it.  What I *think* you're asking about is in reference to the test case of a switch statement.  Typically a switch would be used to test the value of one particular variable, so:
    switch (varTest)
         case "A":
              //Do something here
              break;
         case "B":
              //Do something else here
              break;
         default:
              //Do something cool here instead
              break;
    Are you asking how to use a single switch to test the value of multiple variables (or fields)?  If so, my recommendation would be to simply use and if/else if/else block as you can craft your test cases however you'd like for those.
    Like I said, I may not have understood the issue here so feel free to shoot me an email and I'll take a peek!
    Josh Boyle
    Cardinal Solutions Group
    [email protected]

  • How to use a Table View in AppleScriptObjC

    How can I use a table view and add data to it? And how can I display a button cell and image cell in the table? Thanks.

    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.

Maybe you are looking for

  • Java.lang.NullPointerException (OC4J 10.1.3.1 & JDeveloper 10.1.3.1)

    My project that ran perfectly under JDeveloper 9.0.5.2/OC4J 9.0.2 no loner runs under Jdeveloper 10.1.3.1/OC4J 10.1.3.1. The failure (java.lang.NullPointerException ) is in the following code snippet: =================================================

  • Connecting non HDMI TV

    I have a SD TV that has no HDMI ports but is happily connected to my HD digital receiver/blu-ray (which does have a HDMI port) via standard AV cables. Can I connect my Apple TV thru the HD receiver using a HDMI cable and then watch on my SD TV?  I un

  • ISE integration with SMS gateway required license

    Hello All, We have cisco WLC with guest wireless access configured to use local database. the managment requires new solution to send cridintials to user throug SMS after the user signup through portal. we decided to use the cisco ISE. my question is

  • Mapping Adobe Font lib fonts to Opentype fonts

    I have a customer that has been using Font Folio on a MacOS 9. Now they are converting to PC and want to use opentype instead. They have bought the library package for Opentype. Is there anywhere a listing of mappings of fontnames from the old librar

  • Error when saving files

    My Adobe EXPORTPDF that I have on my computer is not working, I get an error message when saving and it kicks me out when I try to convert PDF's to Word files.  Can someone please contact me asap, 212-896-4672.