Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I need a program that reads prefix expression and return its value. the expressi

ID: 3653556 • Letter: I

Question

I need a program that reads prefix expression and return its value. the expression only contains +,* and single digits. For instance: + 5 * 6 7 returns 47, in other words it multiplies 6 * 7 first then adds 5. Here is my program but it is not working, please fix, thanks. See my program below: import java.util.Scanner; public class lab7 { public static void main (String[] args) { char[] a; a = new char[6]; a[0] = '0'; a[1] = '6'; a[2]= '*'; a[3]= '7'; a[4]='+'; a[5]= '5'; { System.out.print (prefixcalc(a,0)); } public class prefixcalc (char [] a, int i) { if ((int)a[i]>=48&&(int)a[i]<=57)) return a[i]-'0'; //or `(int)a[i]-48 if (int)a[i] == "+")) return (5+prefixcalc(a[i],i+2)); else return (6*prefixcalc(a[i],i+2)) else return 7; } } } } }

Explanation / Answer

import java.util.*; public class PrefixEvaluator { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.println("This program evaluates prefix expressions"); System.out.println("for operators +, -, *, / and %"); System.out.print("Enter expression : "); System.out.println("value = " + evaluate(console)); } // pre : input contains a legal prefix expression // post: expression is consumed and the result is returned public static double evaluate(Scanner input) { if (input.hasNextDouble()) { return input.nextDouble(); } else { String operator = input.next(); double operand1 = evaluate(input); double operand2 = evaluate(input); return evaluate(operator, operand1, operand2); } } // pre : operator is one of +, -, *, / or % // post: returns the result of applying the given operator to // the given operands public static double evaluate(String operator, double operand1, double operand2) { if (operator.equals("+")) { return operand1 + operand2; } else if (operator.equals("-")) { return operand1 - operand2; } else if (operator.equals("*")) { return operand1 * operand2; } else if (operator.equals("/")) { return operand1 / operand2; } else if (operator.equals("%")) { return operand1 % operand2; } else { throw new RuntimeException("illegal operator " + operator); } } }

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote