Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Modern Dental Assisting

Authors: Doni Bird, Debbie Robinson

13th Edition

978-0323624855, 0323624855

Students also viewed these Programming questions

Question

please solve it in c

Answered: 1 week ago

Question

1. What are the peculiarities of viruses ?

Answered: 1 week ago

Question

Describe the menstrual cycle in a woman.

Answered: 1 week ago

Question

Explain methods of metal extraction with examples.

Answered: 1 week ago