Question: import java.util.Scanner; public class PrefixEvaluationTest { public static void main ( String [ ] args ) { Scanner scanner = new Scanner ( System .

import java.util.Scanner;
public class PrefixEvaluationTest {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.println("Prefix Evaluation - Your Name");
String expression;
while (true){
System.out.print("Enter an expression: ");
expression = scanner.nextLine().trim();
if (expression.equalsIgnoreCase("done")){
break;
}
int result = eval(expression);
System.out.println("Evaluates to "+ result);
}
scanner.close();
}
public static int eval(String e){
if (isInteger(e)){// Base case: if e is an integer
return Integer.parseInt(e);
} else {// Recursive case: e starts with "("
int endIndex = e.indexOf(''); // Find the index of the space after the operator
char operator = e.charAt(1); // Extract the operator
String rest = e.substring(endIndex +1); // Extract the rest of the expression
// Parse operands recursively
String operand1= rest.substring(0, rest.indexOf(''));
String operand2= rest.substring(rest.indexOf('')+1);
int result =0;
// Perform the operation based on the operator
if (operator =='+'){
result = eval(operand1)+ eval(operand2);
} else if (operator =='/'){
result = eval(operand1)/ eval(operand2);
}
return result;
}
}
public static boolean isInteger(String str){
try {
Integer.parseInt(str);
return true;
} catch (NumberFormatException e){
return false;
}
}
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!