6

I am using Stack class to calculate simple arithmetic expressions involving integers, such as 1+2*3.your program would execute operations in the order given,without regarding to the precedence of operators. *Thus, the expression 1+2*3 should be calculated (1+2)*3=9,not 1+(2*3)=7.

If i get the input as 1+2*3,i know how to convert the string 1,2,3 to Integer.but i don't know how to covert +,* from string type to operator.

My code logic is: For eg: Given string 2 + (3 * 5), So 3 * 5 will be operated first then +2 will be performed in result of 3 * 5.

  • why can't you do `if(currChar.equals("*"))`? – No Idea For Name Nov 17 '14 at 09:12
  • There's no "operator" type. Invoke the correct operation based on the string value. – Robby Cornelissen Nov 17 '14 at 09:12
  • Ok. If i get (a+b)*c as input what can i do. –  Nov 17 '14 at 09:15
  • @SURESHKUMARS please post your code! we can't do all the work for you – No Idea For Name Nov 17 '14 at 09:21
  • You still have not specified what is your logic to calculate the value of the expression. Just that you are using the Stack class is not enough information. – Chan Nov 17 '14 at 09:21
  • @SURESHKUMARS, to handle brackets '(' and ')' you could split the string up into multiple sections, handling the inner sections first, possibly a recursive function that returns the result. – Eric Nov 17 '14 at 09:22
  • Could you also be more specific about what 'simple' expressions mean? Could you give a few examples? Do your simple expressions have parenthesis yet? If yes, could you supply a few examples of how you would evaluate those expressions. – Chan Nov 17 '14 at 09:30
  • "My code logic is: For eg: Given string 2 + 3 * 5, So 3 * 5 will be operated first then +2 will be performed in result of 3 * 5." --> Thanks. Could you also post the code that is doing this incorrectly so we can suggest the corrections. – Chan Nov 17 '14 at 09:31
  • Look into shunting yard algorithm. It copes with operator precedence and brackets. – weston Nov 17 '14 at 10:21

6 Answers6

7

probably the best way to do it will be equals, but it's best to ignore whitespaces:

i'm not quite sure how you split your string, but for example, if you have a char op and two integer a and b:

String str = op.replace(" ", "");

if(str.equals("*")){
   retVal = a*b;
} else if(str.equals("+")){
   retVal = a+b;
}//etc
No Idea For Name
  • 11,411
  • 10
  • 42
  • 70
  • 3
    Just wondering, is it possible for * to have a lower case form and a upper case form? – committedandroider Nov 17 '14 at 09:16
  • @committedandroider hmm.. probably not, i wanted to ignore whitespaces and thought it does so in ignoreCase. changed it now... – No Idea For Name Nov 17 '14 at 09:19
  • @No Idea For Name I still can't figure what is the current logic the user is using to calculate the value of the expression, what does 'simple' mean when he/she says simple expressions. I mean the original question is yet so undefined and hence I kind of don't understand all these proposed solutions. Just saying.. – Chan Nov 17 '14 at 09:27
  • @Chan i agree with you and for that asked the OP for the code. i want to understand what has he done and what does he expect to receive. – No Idea For Name Nov 17 '14 at 09:30
3

Do what Ogen suggested and manually check the operator. A quick shortcut to doing the if, else if .... structure is switch, that is

switch(operand) {
case "*":
      break;
case "+":
      break; 
 .....
 default:
}
committedandroider
  • 8,711
  • 14
  • 71
  • 126
3

Quick solution: Use below code for executing correct javascript Arithmetic expression in java.

    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine se = manager.getEngineByName("JavaScript");        
    try {
        Object result = se.eval(val);
        System.out.println(result.toString());
    } catch (ScriptException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
Jigar Modi
  • 31
  • 2
2

You will have to manually check and assign the operator. E.g.

if (s.equals("+")) {
    // addition
}
Ogen
  • 6,499
  • 7
  • 58
  • 124
0

Ok, assuming your assignment needs you to use the Stack class and you already have the logic to pick numbers ( including the negative numbers -- that would an operator followed by another operator in all but one cases) and operators and parens, what you could do is as follows.

If you encounter a number, pop the last two elements from your stack. The first item you pop will be an operator and the next will be a number. Evaluate the expression and push it into Stack and continue.

You can ignore the parenthesis. You will also have to handle the case of reading a number or parenthesis the first time.

Chan
  • 651
  • 2
  • 8
  • 15
0

Honestly, I was looking for an answer too. I wanted to make a calculator app so I was trying to turn a string directly into an operation but after looking on the internet for a few hours I found nothing so I ended up making the program myself and since I'm a beginner it wasn't easy. So here s my program it doesn't work with parenthesis or commas . You can only use the four operators "+ - * /" but besides that, everything seems to be working.

It s pretty simple just start with the division by taking both numbers and the string that represent the operand then cut it into three string then do the operation with both numbers after that replace the operation with the result until there s no division left . After that do the same for multiplication , subtraction, and finally addition

here s a description of my functions orderOp : will call the other function getOp : get the string of the operation so if you gave it "2+4*5/6" you'll get 5/6 cutString: cut the string into three part so if you gave it 5/6 you'll get a string array with ["5","/","6"] inside Op: takes the the array of cutString and depending on the arr[1] so in this case "/" it does the math with

class Operateur{
private static final DecimalFormat decfor = new DecimalFormat("0.00");
public static String Op(String s){
    String[] equation = cutString(s);
    double sol = 0;
    switch (equation[1]){
        case "/":
            sol = Double.parseDouble(equation[0])/Double.parseDouble(equation[2]);
            break;
        case "*":
            sol = Double.parseDouble(equation[0])*Double.parseDouble(equation[2]);
            break;
        case "+":
            sol = Double.parseDouble(equation[0])+Double.parseDouble(equation[2]);
            break;
        case "-":
            sol = Double.parseDouble(equation[0])-Double.parseDouble(equation[2]);
            break;
    }
    return sol+"";
}


public static String[] cutString(String s){
    String[] arr = new String[0];
    if(s.contains("+")){
        arr = s.split("((?=[//+])|(?<=[//+]))");
    }
    if(s.contains("-")){
        arr = s.split("((?=-)|(?<=-))");
    }
    if(s.contains("*")){
        arr = s.split("((?=[//*])|(?<=[//*]))");
    }
    if(s.contains("/")){
        arr = s.split("((?=[///])|(?<=[///]))");
    }
    return arr;
}


public static void orderOp(String equation){
    while(equation.contains("/")){
        equation = equation.replace(getOp(equation),(decfor.format(Double.parseDouble(Op(getOp(equation))))).replace(',', '.'));

    }
    System.out.println("Division :" +equation);
    while(equation.contains("*")){
        equation = equation.replace(getOp(equation),decfor.format(Double.parseDouble(Op(getOp(equation)))).replace(',', '.'));
    }
    System.out.println("Multiplication:" +equation);
    while(equation.contains("+")){
        equation = equation.replace(getOp(equation),Op(getOp(equation)));
    }
    System.out.println("addition:" +equation);
    while(equation.contains("-")&& (equation.replaceAll("[^.]", "").length()>1)){
        equation = equation.replace(getOp(equation),Op(getOp(equation)).replace(',', '.'));
        equation = RemoveNegative(equation);
        System.out.println(equation);
    }
    System.out.println("soustraction:" +equation);

}

public static String getOp(String s){
    String r ="";
    if(s.contains("/")){
        int slash = s.indexOf("/");
        int first = slash;
        int last = slash;
        first -= 1;
        while((first >= 0)&&(s.charAt(first) != '+')&(s.charAt(first) != '-')&(s.charAt(first) != '*')&(s.charAt(first) != '/')){
            first -= 1;
        }
        first += 1;
        last += 1;
        while((last < s.length())&&(s.charAt(last) != '+')&(s.charAt(last) != '-')&(s.charAt(last) != '*')&(s.charAt(last) != '/')&&(s.charAt(last) != '/')){//&(last >= s.length())
            if(last < s.length()) {
                last += 1;
            }
        }
        r = s.substring(first,last);
    }
    else if(s.contains("*")){
        int slash = s.indexOf("*");
        int first = slash;
        int last = slash;
        first -= 1;
        while((first >= 0)&&(s.charAt(first) != '+')&(s.charAt(first) != '-')&(s.charAt(first) != '*')&(s.charAt(first) != '/')){
            first -= 1;
        }
        first += 1;
        last += 1;
        while((last < s.length())&&(s.charAt(last) != '+')&&(s.charAt(last) != '-')&&(s.charAt(last) != '*')&&(s.charAt(last) != '/')){
            if(last < s.length()) {
                last += 1;
            }
        }
        r = s.substring(first,last);
    }
    else if(s.contains("+")){
        int slash = s.indexOf("+");
        int first = slash;
        int last = slash;
        first -= 1;
        while((first >= 0)&&(s.charAt(first) != '+')&(s.charAt(first) != '-')&(s.charAt(first) != '*')&(s.charAt(first) != '/')){
            first -= 1;
        }
        first += 1;
        last += 1;
        while((last < s.length())&&(s.charAt(last) != '+')&&(s.charAt(last) != '-')&&(s.charAt(last) != '*')&&(s.charAt(last) != '/')){
            if(last < s.length()) {
                last += 1;
            }
        }
        r = s.substring(first,last);
    }
    else if(s.contains("-")){
        int slash = s.indexOf("-");
        int first = slash;
        int last = slash;
        first -= 1;
        while((first >= 0)&&(s.charAt(first) != '+')&(s.charAt(first) != '-')&(s.charAt(first) != '*')&(s.charAt(first) != '/')){
            first -= 1;
        }
        first += 1;
        last += 1;
        while((last < s.length())&&(s.charAt(last) != '+')&&(s.charAt(last) != '-')&&(s.charAt(last) != '*')&&(s.charAt(last) != '/')){
            if(last < s.length()) {
                last += 1;
            }
        }
        r = s.substring(first,last);
    }

    return r;
}


public static String RemoveNegative(String s){
    s = s.replace("-+","-");
    s = s.replace("+-","-");
    if(s.charAt(0) == '-'){
        s = s.replaceFirst("-","");
        s = s.replace("-","+");
        while(s.contains("+")){
            s = s.replace(getOp(s),Op(getOp(s)));
        }
        s = "-"+s;
    }
    return s;
}

}