Java: Help with postfix assignment! Assign 5: In this assignment, you will creat
ID: 3852155 • Letter: J
Question
Java: Help with postfix assignment!
Assign 5:
In this assignment, you will create an evaluator for postfix expressions. Input: Your program should prompt for and read postfix expressions. Each expression will be on its own line and tokens will be separated by white space. Operators may be (*, 1,-) and perform the expected operation. Assume all integers are positive and there be any invalid characters but the expressions may be not formed correctly. The input ends with an empty line. Processing: You will need to read in each string, parse it into the different tokens (either integer or operator) and then evaluate the expr Output: For each input line, print the original string and then the answer. The result will be an integer. Error handling: You must handle the following errors. 1. Division by zero. 2. Not enough operators in the expression 3. Not enough operands in the expression. Here is an example of input and output. Enter an expression: 15 7+ 1571-22 Enter an expression: 8 1055-/+ 81055-/+ Error: division by zero Enter an expression: 8 1055/ 81055/Error: not enough operandsExplanation / Answer
The answer is as follows:
import java.io.*;
import java.util.*;
public class IntegerStack {
private ArrayList<Integer> ar;
public IntegerStack() {
ar = new ArrayList<Integer>();
}
public void push(int item) {
ar.add(item);
}
public int pop() {
if (!isEmpty())
return ar.remove(size()-1);
else
return -1;
}
public boolean isEmpty() {
return (ar.size() == 0);
}
public int peek() {
if (!isEmpty())
return ar.get(size()-1);
else
return -1;
}
public int size() {
return ar.size();
}
}
The function processLine is as follows:
private static void processLine(String line){
Scanner tokens = new Scanner(line);
IntegerStack stack = new IntegerStack();
char ch;
int a,b;
int error;
String error_message;
while (tokens.hasNext() && error != 1){
ch = sc.next();
if (ch >= '0' and ch <= '9'){
stack.push(Character.getNumericValue(ch));
}
else {
if (stack.size() < 2){
error = 1;
error_message = "Error:Not enough operands"
}
else {
a = stack.pop();
b = stack.pop();
switch (ch) {
case '+':
stack.push(b+a);
case '-':
stack.push(b-a);
case '*':
stack.push(b*a);
case '/':
if (a > 0)
stack.push(b/a);
else {
error = 1;
error_messgae = "Error:Division by zero";
}
}
}
}
}
if (error == 1){
System.out.println(line + " " + error_message);
}
else {
if (stack.size() > 1){
error_message = "Error: Not enough operators";
System.out.println(line + " " + error_message);
}
else {
System.out.println(line + " " + "=" + stack.pop());
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.