Question

In: Computer Science

Must be done in Java. In the 1980s HP produced postfix calculators, which enabled people to...

Must be done in Java.

In the 1980s HP produced postfix calculators, which enabled people to perform arithmetic calculations without using parentheses. The problem was that we had to first learn how to convert a "normal" arithmetic expression (known as an infix expression) to postfix before we could use the calculator.

Then the calculator uses a stack to evaluate the expression . The following tutorial shows you how to use a stack to calculate the result of a postfix expression (and then it has a review of how to convert from infix to postfix. (You need to be able to do this for a test).

This program will use a stack to evaluate postfix expressions. The input file will consist of several postfix expressions, one per line. (I suggest you practice with input from the keyboard initially while you debug your program). In the input file, the operands will be single digit integers. Output the expression and the evaluation. For example, if the input was 23+ you should output "23+ is 5".

Note: You may assume the only things in the input string are digits and operators +,-,*,/

As always, document your program. I expect to see the algorithm written in the comments.

Make sure you put the input file in the correct place in the project, zip the folder and submit it.

I am adding 5 points extra credit to this assignment (that is 25% extra)

To get this extra credit you need to have a method to get the input, one to perform the calculation, and one to output. Put your postfix calculation in a method called postfix. This method will accept a string as parameter (the input string) and return an integer. (either a primitive int or an Integer, your choice).

Rubric:

Comment to state what the program does

Comments within the body of the program

use of try/catch with input file

Correctly declare, initialize, and use a stack

Correct calculation

This criterion is linked to a Learning OutcomeNicely formed output

EXTRA CREDIT. 3 methods (input, postfix, output)

Solutions

Expert Solution

Based on above Question
code Written below

/**
* The code shown below is a Infix to Postfix converter
*/
package com.company; // Replace with your own package and uncomment the line

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.Stack;

public class InfixToPostFixConverter {
/**
* Value holding stack
*/
private Stack1 operandHoldingStack;
/**
* The Character sequence to be extracted
*/
private String input;
/**
* The Character sequence to be returned
*/
private String output = "";
private int result = 0;

/**
* Construct the InfixPostfixStack object
* @param inPutChars input string to be converted
*/
public InfixToPostFixConverter(String inPutChars) {
input = inPutChars;
int stackSize = input.length();
operandHoldingStack = new Stack1(stackSize);
}

/**
* Converts infix to postFix
* @return postfixed string
*/
public String transferToPostFix() {
//The sub-routine to extract characters independently
for (int count = 0; count < input.length(); count++) {
char ch = input.charAt(count);
switch (ch) {
case '+':
case '-':
getOperand(ch, 1);
break;
case '*':
case '/':
getOperand(ch, 2);
break;
case '(':
operandHoldingStack.push(ch);
break;
case ')':
gotParent(ch);
break;
default:
output = output + ch;
break;
}
}
//check if the stack is empty
while (!operandHoldingStack.isEmpty()) {
output = output + operandHoldingStack.pop();
}
//System.out.println(" Test"+output);
return output;
}
// Method to evaluate value of a postfix expression
int postFixEvaluator(String exp) {
//Create the stack to hold calculation
Stack<Integer> value = new Stack<>();

// Scan each character one after the other
for(int k = 0; k < exp.length(); k++)
{
char charAt = exp.charAt(k);

if(charAt == ' ')
continue;
// check for the operand and number here
else if(Character.isDigit(charAt))
{
int n = 0;
// number extraction and storing
while(Character.isDigit(charAt))
{
n = n*10 + (int)(charAt-'0');
k++;
charAt = exp.charAt(k);
}
k--;
//adds the number to the stack
value.push(n);
}

// If the scanned character is an operator, pop two
// elements from stack apply the operator
else
{
int firstInteger = value.pop();
int secInteger = value.pop();
switch(charAt)
{
case '+':
value.push(secInteger+firstInteger);
break;
case '-':
value.push(secInteger- firstInteger);
break;
case '/':
value.push(secInteger/firstInteger);
break;

case '*':
value.push(secInteger*firstInteger);
break;
}
}
}
return value.pop();
}
/**
* The method adds operand to the operandHoldingStack
* @param operandToAdd operand to be added to the
* @param prevIndex the lat index of the operand read
*/
public void getOperand(char operandToAdd, int prevIndex) {
while (!operandHoldingStack.isEmpty()) {
char opOnTopOfStack = operandHoldingStack.pop();
if (opOnTopOfStack == '(') {
operandHoldingStack.push(opOnTopOfStack);
break;
} else {
int previousInternalIndex;
if (opOnTopOfStack == '+' || opOnTopOfStack == '-')
previousInternalIndex = 1;
else
previousInternalIndex = 2;
if (previousInternalIndex < prevIndex) {
operandHoldingStack.push(opOnTopOfStack);
break;
}
else output = output + opOnTopOfStack;
}
}
operandHoldingStack.push(operandToAdd);
}

/**
* Go to the Parent Node
* @param chVal is the character to find the parent node
*/
public void gotParent(char chVal) {
while (!operandHoldingStack.isEmpty()) {
char chx = operandHoldingStack.pop();
if (chx == '(')
break;
else output = output + chx;
}
}
/**
* operand holding stack definition
*/
static class Stack1 {
/**
* the maximum size of the stack
*/
private int maximumSize;
/**
* set of characters
*/
private char[] stackArray;
/**
* index of the value
*/
private int top;

/**
* Constructs the operand holding stack
* @param max is the maximum size of the stack
*/
public Stack1(int max) {
maximumSize = max;
stackArray = new char[maximumSize];
top = -1;
}

/**
* the method add characters to the operand holding stack
* @param charToPush is the character to add to the stack
*/
public void push(char charToPush) {
stackArray[++top] = charToPush;
}

/**
* the method removes characters to the operand holding stack
*
*/
public char pop() {
return stackArray[top--];
}

/**
* the method point on the top of the operand holding stack
*/
public char peek() {
return stackArray[top];
}

/**
*
* @return true if operand holding stack is empty else returns false
*/
public boolean isEmpty() {
return (top == -1);
}
}

/**
* test method
* @param args not necessary in this case
* @throws IOException
*/
public static void main(String[] args) throws IOException {
String input;
String output;
int result;
Scanner br = new Scanner(System.in);
System.out.println("Enter the Infix: ");
input = br.nextLine();
InfixToPostFixConverter toPostFixConverter = new InfixToPostFixConverter(input);
output = toPostFixConverter.transferToPostFix();
System.out.println("Postfix is " + output + '\n');
result = toPostFixConverter.postFixEvaluator(input);
System.out.println("The result are :" + result);
}

}



I have tried my best to resolve it.
If you have any Queries please comment here.
If you like my answer Please Upvote / Like it.
Thank you


Related Solutions

Must be done in Java. In the 1980s HP produced postfix calculators, which enabled people to...
Must be done in Java. In the 1980s HP produced postfix calculators, which enabled people to perform arithmetic calculations without using parentheses. The problem was that we had to first learn how to convert a "normal" arithmetic expression (known as an infix expression) to postfix before we could use the calculator. Then the calculator uses a stack to evaluate the expression . The following tutorial shows you how to use a stack to calculate the result of a postfix expression...
This program must be done in JAVA. Write a program to monitor the flow of an...
This program must be done in JAVA. Write a program to monitor the flow of an item into an out of a warehouse. The warehouse has numerous deliveries and shipments for this item (a widget) during the time period covered. A shipment out (an order) is billed at a profit of 50% over the cost of the widget. Unfortunately each incoming shipment may have a different cost associated with it. The accountants of the firm have instituted a last-in, first...
(must be done in JAVA code) A company dedicated to parking management has decided to renew...
(must be done in JAVA code) A company dedicated to parking management has decided to renew itself by automating its control process since this process is done manually. The company has hired its development team to automate the process and gave it an October 19th deadline until 6 pm. An analyst defined the system requirements as follows: 1. The system must allow configuring the number of spaces that a vehicle parking lot will contain. 2. The system must allow the...
Which of the following is NOT one of the financial statements that must be produced by...
Which of the following is NOT one of the financial statements that must be produced by a public company? A) the balance sheet B) the income statement C) Statement of sources and uses of cash D) Statement of stockholders' equity
PART 1: To target the right age-group of people, a marketing consultant must find which age-group...
PART 1: To target the right age-group of people, a marketing consultant must find which age-group purchases from home-shopping channels on TVs more frequently. According to management of TeleSell24/7, a home-shopping store on TV, about 30% of the online-music-downloaders are in their fifties, but the marketing consultant does not believe in that figure. To test this he selects a random sample of 256 online-music-downloaders and finds 64 of them are in their fifties. 1. The value of the test-statistic is:...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT