I am trying to write a program in Java which takes input a String value like s = "1+27-63*5/3+2" and returns the calculation in integer value
Here below is my code
package numberofcharacters;
import java.util.ArrayList;
public class App {
public static void main(String[] args) {
String toCalculate = "123+98-79÷2*5";
int operator_count = 0;
ArrayList<Character> operators = new ArrayList<>();
for (int i=0; i < toCalculate.length(); i++){
if (toCalculate.charAt(i) == '+' || toCalculate.charAt(i) == '-' ||
toCalculate.charAt(i) == '*' || toCalculate.charAt(i) == '÷' ) {
operator_count++; /*Calculating
number of operators in a String toCalculate
*/
operators.add(toCalculate.charAt(i)); /* Adding that operator to
ArrayList*/
}
}
System.out.println("");
System.out.println("Return Value :" );
String[] retval = toCalculate.split("\\+|\\-|\\*|\\÷", operator_count + 1);
int num1 = Integer.parseInt(retval[0]);
int num2 = 0;
int j = 0;
for (int i = 1; i < retval.length; i++) {
num2 = Integer.parseInt(retval[i]);
char operator = operators.get(j);
if (operator == '+') {
num1 = num1 + num2;
}else if(operator == '-'){
num1 = num1 - num2;
}else if(operator == '÷'){
num1 = num1 / num2;
}else{
num1 = num1 * num2;
}
j++;
}
System.out.println(num1); // Prints the result value
}
}
****The problem is I need to perform calculation according to Order of operations in Math like Multiplication and division first , than addition and subtraction. How can I resolve this? ****
I have used String split() method to seperate the String wherever the operators "+-/*" occurs. I have used character ArrayList to add operators in it. Than at the last portion of code I am looping in that splitted array of Strings and I've initialize int num1 with the first value of splitted array of strings by parsing it to Integer. and int num2 with the second value and the using operators arraylist to perform calculation between them (whatever the operator at that index of arraylist). and storing the result in int num1 and doing vice versa until the end of the string array.
[P.S] I tried to use Collection.sort but it sorts the above arraylist of operators in that order [*, +, -, /]. It puts division at the end while it should put division after or before multiplication symbol