Calculator using JOptionPane

plz tell me what is the error in this code.
my code did not work correctly.
import javax.swing.JOptionPane;
class cal
public static void main(String args[])
String a=null;
String b=null;
String c=null;
JOptionPane.showMessageDialog(null,"Menu","INPUT",JOptionPane.PLAIN_MESSAGE);
JOptionPane.showMessageDialog(null,"Menu","press+ for addition",JOptionPane.PLAIN_MESSAGE);
JOptionPane.showMessageDialog(null,"Menu","press - for subtraction ",JOptionPane.PLAIN_MESSAGE);
JOptionPane.showMessageDialog(null,"Menu","press * for multiplication",JOptionPane.PLAIN_MESSAGE);
JOptionPane.showMessageDialog(null,"Menu","press / for divide",JOptionPane.PLAIN_MESSAGE);
JOptionPane.showInputDialog("enter first value");
JOptionPane.showInputDialog("enter second value");
JOptionPane.showInputDialog("enter operator ");
int i=Integer.parseInt(a);
int j=Integer.parseInt(b);
int k=Integer.parseInt(c);
switch (k)
case'+':
JOptionPane.showMessageDialog(null,"the addition of two number is"+(i+j),"result",JOptionPane.PLAIN_MESSAGE);
break;
case'-':
JOptionPane.showMessageDialog(null,"the subtraction of two number is"+(i-j),"result",JOptionPane.PLAIN_MESSAGE);
break;
case'*':
JOptionPane.showMessageDialog(null,"the multiplication of two number is"+(i*j),"result",JOptionPane.PLAIN_MESSAGE);
break;
case'/':
JOptionPane.showMessageDialog(null,"the division of two number is"+(i/j),"result",JOptionPane.PLAIN_MESSAGE);
default:
JOptionPane.showMessageDialog(null,"ur operator is wrong","INPUT",JOptionPane.PLAIN_MESSAGE);
}

I'll tell you one thing more, then I'm off. Replace:
int i=Integer.parseInt(a);
int j=Integer.parseInt(b);
int k=Integer.parseInt(c);... With:
int i=Integer.parseInt(JOptionPane.showInputDialog("enter first value"));
int j=Integer.parseInt(JOptionPane.showInputDialog("enter second value"));
char[] chars = JOptionPane.showInputDialog("enter operator ").toCharArray();
char k=chars[0];~Bill

Similar Messages

  • Using JOptionPane to exit program & Using toString method

    Hello,
    In my program I have to use a toString method below
    public String toString(Hw1NCBEmployee[] e)
            String returnMe = String.format(getStoreName() + "\n" + getStoreAddress() + "\n" + getCityState() +  "\nYou have " + getEmpCount() + "employee(s)");
            return returnMe;
    }Now, at first, when I initially tested my code, it was working just fine, printing out the right way
    Point is -- now that Im practically finished with my program, and am going back and running it - calling the toString method gives me the address rather than the information . . . Can anyone help me with this issue??
    Also, Im using JOptionPane to display everything, but -- at first, it worked fine, then (around the same time I started having the above problem) it stopped exiting the do-while loop:
    while(go)
                 int option = JOptionPane.showConfirmDialog(null, "Do you want to enter employee information?", "Welcome!", JOptionPane.YES_NO_OPTION);
                     if(option == JOptionPane.NO_OPTION)
                        go = false;  //exit loop
            

    ncjb wrote:
    well, for the toString - I have to print out the info inside the array -- am I right in thinking that the only way to do this is to pass in the array ??If the array is part of the class then there is no need to pass it as a parameter. If it is being passed in from outside the class then I have to question your design. Why should class X being formatting data that is not a representation of itself?
    and i have 2 other files that go with this program . . . I just want to know if there is a way to make sure that when the user presses the NO option, it will exit the loop -- the piece of code you see if apart of an entire method (not long) -- do you want me to include this??You read that link I provided REAL quick!

  • Using JOptionPane in a non-event dispatching thread

    I am currently working on a screen that will need to called and displayed from a non-event dispatching thread. This dialog will also capture a user's selection and then use that information for later processing. Therefore, the dialog will need to halt the current thread until the user responds.
    To start, I tried using the JOptionPane.showInputDialog() method and set the options to a couple of objects. JOptionPane worked as advertised. It placed the objects into a combobox and allowed the user to select one of them. However, it also gave me something unexpected. It actually paused the non-event handling thread until the user had made a selection. This was done without the JOptionPane code being wrapped in a SwingUtilities.invokeLater() or some other device that would force it to be launched from an Event Handling Thread.
    Encouraged, I proceeded to use JOptionPane.showInputDialog() substituting the "message" Object with a fairly complex panel (JRadioButtons, JLists, JTextFields, etc.) that would display all of the variety of choices for the user. Now, when the screen pops up, it doesn't paint correctly (like what commonly occurs when try to perform a GUI update from a non-event dispatching thread) and the original thread continues without waiting for a user selection (which could be made if the screen painted correctly).
    So, here come the questions:
    1) Is what I am trying to do possible? Is it possible to create a fairly complex GUI panel and use it in one of the static JOptionPane.showXXXDialog() methods?
    2) If I can't use JOptionPane for this, should I be able to use JDialog to perform the same type function?
    3) If I can use JDialog or JFrame and get the threading done properly, how do I get the original thread to wait for the user to make a selection before proceeding?
    I have been working with Java and Swing for about 7-8 years and have done some fairly complex GUIs, but for some reason, I am stumped here. Any help would be appreciated.
    Thanks.

    This seems wierd that it is functioning this way. Generally, this is what is supposed to happen. If you call a JOptionPane.show... from the Event Dispatch Thread, the JOptionPane will actually begin processing events that normally the Event Dispatch Thread would handle. It does this until the user selects on options.
    If you call it from another thread, it uses the standard wait and notify.
    It could be that you are using showInputDialog for this, try showMessageDialog and see if that works. I believe showInputDialog is generally used for a single JTextField and JLabel.

  • Designing a calculator using selection screen(abap)

    hi i just now stepped into this technology. iam learning abap.  i like to jknow how to design a calculator using selection screen. 
    could any one give your  suggestions or any sites having such example programs . 
    thankyou

    Hi
    Welcome to SDN.
    Use the sample peace of code for design Calculator.
    Hi,
    Create push buttons for the + , - , / , * , = in your dialog program.
    Create an input field with the data type that can accept decimal places..
    When the enter 12 then press the push button "+" button store the value 12 in a variable v1..Then clear the input field..
    Then when the user enters another number..lets say "13"..
    Then if the user presses the "=" button...Then sum the values from the variable v1 with the input field..
    Hope this helps..
    Check this sample code..
    MODULE USER_COMMAND.
    CASE SY-UCOMM.
    WHEN 'ADDITION'.
    ASSUMING THE INPUT FIELD NAME IS P_INPUT.
    V_V1 = P_INPUT.
    V_OPERATION = '+'.
    CLEAR: P_INPUT.
    WHEN 'EQUALTO'.
    CASE V_OPERATION.
    ADDITION
    WHEN '+'.
    SUM UP THE VALUES.
    P_INPUT = P_INPUT + V_V1.
    ENDCASE.
    MULTIPLICATION
    WHEN '*'.
    MULTIPLY UP THE VALUES.
    P_INPUT = P_INPUT * V_V1.
    ENDCASE.
    ENDCASE.
    ENDMODULE.
    Regards,
    Sree

  • Interactive ROI Calculator using Flash Catalyst?

    Hello, a client of ours has asked us to create an interactive ROI calculator similar to the one in the following link:
    http://bit.ly/98vjCF
    Our design and production department does work in Flash, mainly to create simple web banners, however they're not hardcore Flash developers by any means. We'll be upgrading from CS4 to CS5 with Catalyst soon. Is it possible to create an interactive ROI calculator using this software or would using a seasoned Flash developer be a better choice?
    Thanks for any info.
    henry

    Hi Henry,
    You can use Flash Catalyst to design the UI of your calculator, both for protyping and optionally for final production too.  However, to do the actual calculations you'll have to write a bit of code using another tool.  For example, you can import the Catalyst project into Flash Builder and wire up the calculation logic to the UI you've created.  This gives you the option of having a nontechnical designer work on the UI, while a less design-oriented developer writes code without having to worry much about the visuals.
    The underlying code used in a Catalyst project is Flex 4.  This should be a snap for a seasoned Flash developer to work with.  Or, a Java or JavaScript developer should also be able to get up to speed on Flex pretty easily (especially if the UI was already built in Catalyst and the dev is just wiring up the "business logic").
    Hope that helps,
    - Peter

  • How to use JOptionPane in jsp, instead of javascript message alert box?

    HI,
    How to use JOptionPane in jsp,
    instead of javascript "message alert box"?
    I hate javascript,
    I'd like to only use java in jsp. don't use javascript.
    javascript is client side,
    jsp is server side. i know that.
    how to... instead of javascript box?
    how to use ... message box in webpage?
    don't use applet,,,, don't use javascript,,,
    hm...zzzZzz
    I hate javascript..T.T
    <SCRIPT language=JavaScript>
    alert("hate javascript");
    </SCRIPT>
    ===>>>>
    In this way,,
    JOptionPane.showOptionDialog(null,"I love java")
    I'd like to only use jsp and java and html...in webpage.
    don't use javascript....
    Why? don't sun provide message box in jsp, instead of javascrip box?
    Why?
    Edited by: seong-ki on Nov 4, 2007 8:38 PM

    Drugs are bad, m'kay?

  • Trying to print a list using JOptionPane

    I am very new to Java and programming, so please forgive me if this should be apparent. I wrote a program for school which was for ordering pizzas. I wrote it as a console program and after much frustration it finally worked. Now I am trying to change it to a GUI program using JOptionPane. I was hoping that since I already had the logic written and working, I could focus on the GUI aspect. I was wrong. I want to print a list of enums on a JOptionPane and cannot figure out how to do it My code in the console program was:
    System.out.println("The available crust styles are: ");
         for(Pizza.Style style : Pizza.Style.values())
              System.out.println(style+" ");
    So how can I iterate through the for loop to list all of the styles in the JOptionPane? Do I need to turn it into a method with a return and then cal the method like
    JOptionPane.showMessageDialog(null, crustMethod()); ??

    OP said:
    ... Now I am trying to change it to a GUI program using JOptionPane. I was hoping that since I already had the logic written and working, I could focus on the GUI aspect. I was wrong. ...I wouldn't use JOptionPane. You need JFrame and maybe, but I doubt it, a JDialog. OP, the GUI is more than likely to be nothing more than a form that allows users to set certain properties or fields in a Java class. For example let's say we have this class.
    public class Point
      public int x;
      public int y;
    }Then a GUI for this would be something like a JPanel with two (2) JLabels and two (2) JTextFields. Maybe something like so...
    import java.awt.*;
    import javax.swing.*;
    public class PointGUI extends JPanel
      public JLabel xLabel = new JLabel("Coordinate X:");
      public JLabel yLabel = new JLabel("Coordinate Y:");
      public JTextField xField = new JTextField(4);
      public JTextField yField = new JTextField(4);
      public PointGUI(){
        setLayout(new GridLayout(2, 2));
        add(xLabel);
        add(xField);
        add(yLabel);
        add(yField);
    }Then to run the program...
    import javax.swing.*;
    public class Test
      public static void main(String[] args){
        SwingUtitlities.invokeLater(new Runnable(){
          public void run(){
            PointGUI gui = new PointGUI();
            JFrame f = new JFrame("PointGUI");
            f.getContentPane().add(gui, "Center");
            f.pack();
            f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
            f.setVisible(true);
    }... actually all the program does is display the GUI. But, can you see that the GUI's JLabels and JTextFields describe all the public properties of the Point class? Can you see that the entire GUI can be placed anywhere in a JFrame, or maybe even in a JDialog? From this point on, you can add other functions and features to your classes, GUI's and the main apps that run them.
    A hint on your project, you may need to write a Pizza class that decribes all the things a single pizza can be - then come up with a GUI for that and an app that runs it.

  • Creating a ad-hoc calculation using sql query

    Hi All,
    I want to know if its possible some way to create a ad-hoc sql query inside a workbook so as to create a calculation using that sql.
    I have a folder which gives me balance for any period. My requirement is to display current period balance along with prior years closing balance in same record for each code combination. I dont want to modify folder definition.
    Thanks for your inputs.
    Vishal.

    You could try creating a custom function for this purpose. You would need to register the function in the End User Layer and then you can call the function from your report.

  • Calculations using Physical Tables vs Logical Tables

    It's easy to find an example of where you would want to use Logical Tables instead of Physical Tables to create fact columns in the repository. Any measure such as Profit Margin (i.e. Profit / Sales) must be computed in the Logical Tables, so that the division operation occurs after the dimensional aggregations are passed to it from the physical layer. In the example of (Profit / Sales), using Physical Columns returns an incorrect result, because it does the division operation first, then aggregates all of those results into a nonsense value.
    So, is there some type of formula in which the reverse is true, such that using Logical Tables would return an incorrect result, while the Physical Tables would return the correct result?
    If not, then under what circumstances would we want to use the Physical Tables instead of the Logical Tables? Is there some type of formula that performs better with Physical Tables?

    Hi Thomson,
    calculations using physical columns generate fair SQL which wouldn't involve any sub-selects in physical query... and would be fast.
    If you use logical columns by selecting the “Use existing logical columns as the source check box" in rpd, most of the times it generates queries.. with sub-selects (means subqueries)
    Ex: suppose you are calculating a calculation based on 2 columns a, b then
    If you use, Logical columns, the query would be something like...
    *Select D1.C1 + D1.C2*
    *From (select Sum(X) as C1,*
    *Sum(Y) as C2*
    *From FactX) D1*
    *Group by DimY*
    If you use, phyiscal columns for calculation the... the query would be...
    *Select Sum(D1.C1 + D1.C2)*
    *From FactX*
    *Group By DimY;*
    which is much preety and good to query the database... without any difficult..
    For first query... it's using inner queries... so process would be slow...
    +Thanks & Regards+
    +Kishore Guggilla+

  • Deleting a MS Access database table record using JOptionPane

    hi!
    just want some help here..
    is there a way to delete a MS Access database record through using JOptionPane?? i've gone through some, probably alot of examples on SELECT, INSERT, UPDATE, DELETE statements but none came up to the stuff i need.
    so far i've seen the DELETE statement like this and also this is a common DELETE statement..
    statement.executeUpdate("DELETE FROM tableName WHERE fieldName01 = 'blablabla' AND fieldName02 = 'etcetcetc'");like INSERT, there's a coding somewhat like this:
    String asd = JOptionPane.showInputDialog(null, "Enter blablabla stuff");
    statement.executeUpdate("INSERT INTO whatEverTableName (tableFieldName) VALUES('"+asd.getText()+"')");so, is it possible using the same method for DELETE??
    help and advices are appreciated in advanced..

    Here's how I did it. Research does help, but sometimes looking at others code does too... You do have to have a dummy file that you made with access though. You can't just make a file file.mdb (it will be corrupt)
         public void createDatabase(String database) throws SQLException{
              try{
                   // This file needs to have been created with MS Access
                   File dbfile = new File(this.dataBaseDir + "dummy.mdb");
                   // This is the new database file being made
                   File newFile = new File(this.dataBaseDir + database + ".mdb");
                   // Copy all bytes from dummy file to new DB file.
                   FileInputStream instream = new FileInputStream(dbfile);
                   FileOutputStream ostream = new FileOutputStream(newFile);
                   int numBytes = instream.available();
                   byte inBytes[] = new byte[numBytes];
                   instream.read(inBytes, 0, numBytes);
                   ostream.write(inBytes, 0, numBytes);
              catch(FileNotFoundException e) { e.printStackTrace();}
              catch(IOException e) { e.printStackTrace();}
              if(DEBUG) System.out.println("creating the " + database + " database");
         }

  • Explain How delivery date is calculated using backward and forward schedul

    How can anyone please explain how delivery date is calculated using forward and backward scheduling
    I want to have it broken down into the following steps
    for eg for delivery date calculation following dates are used
    Material Availabilty Date
    Material Staging Date
    Pick/pack time
    Transportation PLanning date
    Loading date
    Goods issue date
    Transit Date
    Delivery Date
    Can some one please give me an example and explain wht these dates are
    for eg customer needs delivery date on  11/20/2008
    how would the system cacluate whether it can meet the delivery date using backward scheduling
    and if it doesnt meet how does the system do the forward scheduling
    also i am not clear with the following dates
    material avaialibilty date
    material staging date
    transportation date
    can some one please explain me all this in detail
    Thanks

    Hi,
    Basically this is the CRSD(Customer requested ship date logic)logic in which system calculates the ship date depends upon the material availability. If material is available system calculates ship date on the basis of master data maintained in customisation.Master data is maintained in the  following link.
    If material is not available then system takes into consideration vendor delivery date & then calculate customer ship date.
    Please go through the link in SPRO
    LE-Shipping -Basic shipping functions-Scheduling -Delivery scheduling & Transportation scheduling-Maintain duration.
    In customisation following data is maintained
    Material Availabilty Date
    Material Staging Date
    Pick/pack time
    Transportation PLanning date
    Loading date
    Goods issue date
    Transit Date
    Delivery Date
    Hope you got the idea of CRSD calculation
    Regards,
    Prashant.

  • Comple errors using JOptionPane

    I'm trying to write a Java program using JOptionPane dialog/display boxes that reads an integer and checks whether it is even using true/false statements. I also want the program must check if the number the user entered is between 1 and 1000.
    I haven't found alot of help in the book I have and i've found some help in another forum but it doesn't seem to compile well, I get the following errors:
    IntegerRead.java:39: cannot find symbol
    symbol : method valueOf(java.lang.String)
    location: class Integer
    int number = Integer.valueOf(s);
    ^
    Integer.java:13: cannot find symbol
    symbol : class Scanner
    location: class Integer
    Scanner input = new Scanner( System.in );
    ^
    Integer.java:13: cannot find symbol
    symbol : class Scanner
    location: class Integer
    Scanner input = new Scanner( System.in );
    Here is the code:
    // Assignment 2.1: IntegerRead.java
    // This program reads an integer, checks if it's even and is between 1 and 1000.
    import javax.swing.JOptionPane; // program uses class JOptionPane
    public class IntegerRead
    public static boolean isNumber(String args)
    if(args.length() > 3)
    throw new IllegalArgumentException("Invalid argument");
    else
    boolean isNumber = false;
    for(int i = 0; i < args.length(); i++)
    char c = args.charAt(i);
    if(Character.isDigit(c))
    isNumber = true;
    else
    isNumber = false;
    return isNumber;
    public static boolean isEven(int aNumber)
    int a = aNumber & 1;
    return (a == 0);
    public static void main(String args[])
    String s = JOptionPane.showInputDialog("Please enter number between 0 to 999");
    System.out.println("Is Number " + isNumber(s));
    if(isNumber(s))
    int number = Integer.valueOf(s);
    System.out.println("Number " + number + "is Even " + isEven(number));
    for(int i = 0; i < 999; i++)
    System.out.println(i + " is " + isEven(i));
    I know i'm missing very simple. I'm new and have tried to build upon what I have so far, but I can't figure it out.
    Thanks....
    Edited by: Scott.Dishman on Jul 9, 2008 4:07 PM

    You have a class named Integer somewhere on your class path. Get rid of it or rename it. If you've already renamed your Integer.java file, you still need to delete the Integer.class file. You should never create your own class that has the same name as a class in the standard java.lang package.

  • Mathematical calculations using BigDecimal

    Hi all,
    I am doing some mathematical calculations using float variables. They are not working properly because of rounding issues....So, before I change the whole program to do the same calculations using BigDecimal, just wanted to check out whether there are any catches in that also. Like, is it safe if I do BigDecimal.add, subract etc. instead of addding the floating point numbers directly.....Can I be assured that the results will be precise, to 2 decimal places?
    Any help will be appreciated...
    Thanks

    The "catch" is that computers do not work with real numbers. They work with representations of real numbers like finite decimals or fractions. My advice is to continue to use doubles, but do not expect infinitely precise results and round the values when outputting them.

  • Using JOptionPane.showInputDialog to return an integer

    I am currently using JOptionPane to return a string from the Object array i made with all possible choices.
         private static boolean determineService(){
              JLabel label;
              label=new JLabel("Please select which Service Model to use.",JLabel.CENTER);
              Object[] possibilities = {"AddressCleanse", "VIN", "PostalCode"};
              serviceModel = (String)JOptionPane.showInputDialog(
                                  null,
                                  label,
                                  "Select Service",
                                  JOptionPane.PLAIN_MESSAGE,null,
                                  possibilities,
                                  "AddressCleanse");
    //          If a string was returned, say so.
              if ((serviceModel != null) && (serviceModel.length() > 0)) {
                  System.out.println("You've selected " + serviceModel + "!");
                  setVariables();
                  return true;
              }else{
    //               If you're here, the return value was null/empty.
                   System.out.println("Null or Bad service selected!\n Exiting program.");
                   return false;
              }I would like to instead return the response as an integr so I can then use a switch, rather than recursive if, else if logic.
    Apparently java doesnt allow switches to use strings (like PHP does)
    any ideas?

    Just a question more than an answer: would using a hashmap ever work here? where the key is a string and the value is an (???) object that implements an interface that would allow you to call an appropriate method? Perhaps one could use the keySet() and toArray to build the Object array for the JOptionPane. I thought I read something about this somewhere, but am not sure....

  • Calculator using swing

    hello everyone,
    I am new toprogramming and alst to java language. can anybody help me in writing calculator using java swing.
    the functionality of the calculator should be same as the one we use in windows operating system
    please help me

    please help meSure, what problem to you have?
    if you are starting from scratch, get a copy of this book
    http://www.amazon.com/gp/product/1931841608/qid=1144486744/sr=2-1/ref=pd_bbs_b_2_1/002-4043290-4676869?s=books&v=glance&n=283155
    which builds a calculator throughout the book

Maybe you are looking for

  • Weblogic Admin Server not starting after Virtual Server move

    Hi, we've migrated a VMware virtual server, and our Weblogic Admin (and managed IRM server) no longer start. The associated log files don't get updated and only the following info is present in the Command window, which I can only see if I use the /k

  • Missing File Messages / iWeb adding -1 to files names

    I am trying to create a website using iWeb '09 but I am have an issue with missing file messages. I created the site without an issue. Opened it up the following day and immediately received missing file messages for almost all pages on the site. iWe

  • Reg:Seeburger BIC code list file

    Hello All, I need the seeburger code-list files for the following version in EDIFACT, 0065EDIFACT_UN_D06B.cgprop and 0052EDIFACT_UN_D06B.cgprop.Please guide me. Thanks, Kishore

  • Game Sessions at JavaOne(tm) 2002

    This is the JavaOne event for this year. Does anyone know if there will be video / transcripts of the sessions? I am in NY and won't be able to make it . But i would really like to get video or transcript of this event. Game Sessions at JavaOne(tm) 2

  • Premiere Elements 3.0.2 Quicktime Export Crash

    I haven't used Premiere Elements 3.0.2 in a few months, but now I want to export something I was working on as a Quicktime movie. However, whenever I choose the "Quicktime" option from the Export menu, the entire program just closes without any error