QuestionQuestion

Given the following input file, evaluate the postfix expression on each line, printing out the elements and the results as show in the sample output below for each line. The algorithm is given in Notes 6, point I.F.
Each line of the input ends with "end", so input using the next() method of the Scanner until the input is "end" (remember to use the .equals method for String comparisons).
Use a java.util.Stack<Integer> to store the integer values.
Write a boolean method to determine if a String is an operator.
To apply the operator, remember that a switch statement can have case values that are Strings. Also remember that you pop the right operand first, then the left one.

Sample output:
56*3+274-*- evaluates to 27
73*1-5* 50+ evaluates to 150
12 10 6 - / 25 * evaluates to 75
39 4- 7/20 + evaluates to 25
3456+ * + evaluates to 47
120 5032+//3 + evaluates to 15
Press any key to continue...

Input file:
5 6 * 3 + 2 7 4 - * - end
7 3 * 1 - 5 * 50 + end
12 10 6 - / 25 * end
39 4 - 7 / 20 + end
3 4 5 6 + * + end
120 50 3 2 + / / 3 + end

Solution PreviewSolution Preview

These solutions may offer step-by-step problem-solving explanations or good writing examples that include modern styles of formatting and construction of bibliographies out of text citations and references. Students may use these solutions for personal skill-building and practice. Unethical use is strictly forbidden.

public static int evaluate(String s) {
Stack<Integer> st = new Stack<Integer> ();
Scanner sc = new Scanner(s);
while (sc.hasNext()) {
if (sc.hasNextInt())
st.push(sc.nextInt());
else {
int num2 = st.pop();
int num1 = st.pop();
String op = sc.next();
if(isOperator(op)) {
switch(op) {
case "+":
st.push(num1 + num2);
break;...

By purchasing this solution you'll be able to access the following files:
Solution.java.

$15.00
for this solution

or FREE if you
register a new account!

PayPal, G Pay, ApplePay, Amazon Pay, and all major credit cards accepted.

Find A Tutor

View available Java Programming Tutors

Get College Homework Help.

Are you sure you don't want to upload any files?

Fast tutor response requires as much info as possible.

Decision:
Upload a file
Continue without uploading

SUBMIT YOUR HOMEWORK
We couldn't find that subject.
Please select the best match from the list below.

We'll send you an email right away. If it's not in your inbox, check your spam folder.

  • 1
  • 2
  • 3
Live Chats