Question

I have a basic calculator that is set so when the equal button is pressed then the JTextField is saved in a string form, that's the problem, it's in string form so I do not know how to solve the equation. I've tried using the JavaScript Engine but cannot figure that out. Any help?

//actionListener
@Override
public void actionPerformed(ActionEvent e) {

    if(e.getSource().equals(oneButton)){
        input1 = 1;
        text.setText(text.getText()+input1);}
    else if (e.getSource().equals(twoButton)){
        input2 = 2;
        text.setText(text.getText()+input2);}
    else if(e.getSource().equals(threeButton)){
        input3 = 3; 
        text.setText(text.getText()+input3);}
    else if(e.getSource().equals(fourButton)){
        input4 = 4; 
        text.setText(text.getText()+input4);}
    else if(e.getSource().equals(fiveButton)){
        input5 = 5;
        text.setText(text.getText()+input5);}
    else if(e.getSource().equals(sixButton)){
        input6 = 6;
        text.setText(text.getText()+input6);}
    else if(e.getSource().equals(sevenButton)){
        input7 = 7;
        text.setText(text.getText()+input7);}
    else if(e.getSource().equals(eightButton)){
        input8 = 8;
        text.setText(text.getText()+input8);}
    else if(e.getSource().equals(nineButton)){
        input9 = 9;
        text.setText(text.getText()+input9);}
    else if(e.getSource().equals(zeroButton)){
        input0 = 0;
        text.setText(text.getText()+input0);}
    else if(e.getSource().equals(plusButton)){
        text.setText(text.getText()+" + ");}
    else if(e.getSource().equals(minusButton)){
        text.setText(text.getText()+" - ");}
    else if(e.getSource().equals(timesButton)){
        text.setText(text.getText()+" * ");}
    else if(e.getSource().equals(dividButton)){
        text.setText(text.getText()+" / ");}
    else if(e.getSource().equals(clrButton)){
        text.setText("");}
    else if(e.getSource().equals(enterButton)){
        eq = text.getText();
//trying the javascript     ScriptEngineManager mgr = new ScriptEngineManager();
        ScriptEngine engine = mgr.getEngineByName("JavaScript");

            try {
                text.setText((String) engine.eval(eq));
            } catch (ScriptException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

    }
Was it helpful?

Solution

If order of operations matter you're going to have to use a stack. If you're only calculating from left to right, you should be fine.

As @Ericson Willians answer, you convert a String to an int or double via:

    String str = text.getText();
    Integer.parseInt(str);
    Double.parseDouble(str);

But, you're likely to run into trouble here because when you press the enter button, you are getting the entire equation you placed in your your text element, aka if you pressed enter and you had the equation stored as "2 + 3", your text.getText() will give you "2 + 3" and you will not be able to use the following without giving you an error.

    Integer.parseInt(text.getText()); //NumberFormatException For input string: "2 + 3"
    Double.parseDouble(text.getText()); //NumberFormatException for "2 + 3"

You're going to have to break up the string in a specific way before you can convert the strings into integers or doubles. A good way to break up the string would be to use something like:

String st = text.getText();
//Example: String st = "2 + 3";
//remove white space
st = st.replaceAll("\\s","");
//might have to change to allow for negative numbers
String[] splitStrings = (st.split("((?<=[+-/*])|(?=[+-/*]))")); 
//Example: splitStrings is now -> ["2","+","3"]

This breaks up the string between operations. You can then get the elements you want and parse them as integers. So for example:

int result;
int left = Integer.parseInt(splitStrings[0]);
String op = splitStrings[1];
int right = Integer.parseInt(splitStrings[2]);
if(op.equals("+")){
    result = left + right;
}
text.setText("" + result);

But, since the equation could be big, you should probably create a loop that does something like this and you're going to need an if statement or a switch statement for all the operations.

OTHER TIPS

You can write a calculator that parses strings using antlr: http://www.antlr.org/

Why don't you just use the parse method from the Integer and Double classes?

int integerNumber = Integer.parseInt(text.getText());
double doubleNumber = Double.parseDouble(text.getText());

As you can see, the method parseInt() from the Integer class converts the string in an Integer, and the same happens with Double. After doing this you can perfectly make any math with your strings.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top