Question
Build a calculator that ignores order of operations. This calculator will read in a String from the user & calculate the results from left to
Build a calculator that ignores order of operations. This calculator will read in a String from the user & calculate the results from left to right. Consider the following input and output:
"4 + 4 / 2"
"Answer is 4" //not 6, since the addition occurs first when reading from left to right
1 * -3 + 6 / 3
Answer is 1 //not -1, Start your program by copying the driver code below.
Read the program below and notice the comments before you proceed! Begin by tracing (i.e. reading through) the program in main. Your code will go in the calculate() function, so start writing code there. Hints:
- Build the starter code using a snippet below.
- Assume spaces between all numbers and operators.
- If a number is negative (like -3), there will be no space between the sign and the number. Use Scanner and nextInt() to read each integer.
- Use Scanner and what operation to read a single character? (our operator?).
- Or you could also use StringTokenizer to do these tasks as well.
- To get started use the following code template below.
SAMPLE CODE TO USE:
import ?; /* * Complete the calculate() function below to build a simple, infix * calculator that evaluates a compound expression from left to right, * regardless of operator precedence */ public class InFixCalc { //example pattern: "3 + 5" //general pattern:
public static void main(String[] args) { //String input = "4 + 4"; //String input = "4 + 4 / 2"; //String input ="1 * -3"; String input ="1 * -3 + 6 / 3"; //String input ="5"; //String input ="-5"; int answer = calculate(input); System.out.println("Answer is " + answer); }
//preconditions: all binary operations are separated via a space //postconditions: returns the result of the processed string public static int calculate(String input) { int lhs,rhs; //short for left-hand & right-hand side char operation; /*todo: your name and code goes here*/ /*You need a Scanner(or StringTokenizer) to get tokens *Then you need a loop, and switch inside that loop*/ return lhs; } }
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