Question: How would I fix my code to evaluate the string input in order of operations, i.e. * and / operators first? At the moment it

How would I fix my code to evaluate the string input in order of operations, i.e. * and / operators first? At the moment it is going through my string input chronologically.

public class InlineParsing {

public static void main(String []args){

String input = "5-2*20+5+11/10";

input = input.replace(" ","");

String parsedInteger = "";

String operator = "";

int aggregate = 0;

for (int i = 0; i < input.length(); i++){

char c = input.charAt(i);

if (Character.isDigit(c)) {

parsedInteger += c;

}

if (!Character.isDigit(c) || i == input.length()-1){

int parsed = Integer.parseInt(parsedInteger);

if (operator == "") {

aggregate = parsed;

}

else {

if (operator.equals("*")) {

aggregate *= parsed;

}else if (operator.equals("/")){

aggregate /= parsed;

}

}

if (operator.equals("-")) {

aggregate -= parsed;

} else if (operator.equals("+")) {

aggregate += parsed;

}

parsedInteger ="";

operator = ""+c;

}

}

System.out.println("Sum of " + input+": " + aggregate);

}

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!