Question
Extend the expression evaluation example so that an expression with the following operators +, -, *, /, (, and ) can be properly evaluated for
Extend the expression evaluation example so that an expression with the following operators +, -, *, /, (, and ) can be properly evaluated for integer values and double values. Note that your program needs to preserve integer division correctness. For example, 5/10 is 0 instead of 0.5.
Code:
import java.util.Stack; import java.util.Scanner;
public class EvaluateExpression2 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter an arithmetic expression: "); String expr = input.nextLine(); System.out.println(expr + " = " + evaluateExpression(expr)); } //TODOs: Adjust the two methods in the example to adapt to possible double operands
public static String insertBlanks(String s) { String result = "";
for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '(' || s.charAt(i) == ')' || s.charAt(i) == '+' || s.charAt(i) == '-' || s.charAt(i) == '*' || s.charAt(i) == '/') result += " " + s.charAt(i) + " "; else result += s.charAt(i); }
return result; } }
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