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
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started