Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

More Books

Students also viewed these Databases questions

Question

What is the Definition for Third Normal Form?

Answered: 1 week ago

Question

Provide two examples of a One-To-Many relationship.

Answered: 1 week ago