3. Write an intStack interface that describes the abstract data type of a stack
ID: 641324 • Letter: 3
Question
3. Write an intStack interface that describes the abstract data type of a stack of int values. Assume you have a class MyIntStack that implements this interface (you do not need to write it). Using this interface, write a program that evaluates a postfix arithmetic expression with single-digit integer operands and operators '-', '+','*', and '/'. For simplicity, assume that your input string representing the expression does not have any errors (e.g., is valid - no error detection is needed), and that it contains only digits and operator characters (e.g.. no spaces). You can use a string method charAt(int n) - look it up. (3 pts) public static int postfixExpr (String expr) { ???? }Explanation / Answer
import java.util.*;
public class PostfixExpr
{
static Scanner console = new Scanner(System.in);
public static void main(String [] args)
{
char ch = 0;
int rand1 = 0;
int rand2 = 0;
int temp;
int result = 0;
String str;
System.out.print("Enter the expression: ");
str = console.nextLine();
Stack aStack = new Stack(str.length());
//enters the string into the stack and
//converts the appropriate char to digits;
//and then completes the appropriate
//operations
for(int i = 0; i < str.length(); i++)
{
ch = str.charAt(i);
if(Character.isDigit(ch))
{
temp = Character.getNumericValue(ch);
aStack.push(temp);
}//end if
if((ch == '+' || ch == '-' || ch == '*' || ch == '/'))
{
rand2 = aStack.pop();
rand1 = aStack.pop();
if(ch == '+')
result = rand1 + rand2;
else if(ch == '-')
result = rand1 - rand2;
else if(ch == '*')
result = rand1 * rand2;
else if(ch == '/')
{
if(rand2 == 0)
System.out.println("ERROR: divide by zero");
else
result = rand1 / rand2;
}
aStack.push(result);
}//end if
}//end for
if(aStack.count() == 1)
{
result = aStack.pop();
System.out.print("The result is: " + result);
}
else
System.out.println("ERROR: not enough operands");
}//end of main
}//end PostfixExpr
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.