Assign a new alphabet whenever it sees a new number in those expressions ( Use i
ID: 3792845 • Letter: A
Question
Assign a new alphabet whenever it sees a new number in those expressions ( Use increment operator(++) so, lets say if x = "a", then x++ would be "b" and so on for as many numbers are there in expressions)
Assignment:Consider the input file “p4in.txt”has the following contents (in java language)
(Assuming that all expressions are correct): so using the valueStack ,uses ArrayStack and operatorStack
Specifications:
1) You must implement ArrayStack.java and modify Positfix.java so that valueStack uses ArrayStack and operatorStack uses LinkedStack.
2) Do this program step by step.
3) It may be easier to use String to split the expression to obtain the array of values.
4) Build your symbol table using single-letter variable name that starts from ‘a’.
Here is the inputfile (p4in.txt)
2 + 3
(2+ 3) * 4
2 * 3 / (4 -5)
2 / 3 + (4 -5)
2 / 3 + c -d
2 ^ 3 ^ 4
(2 ^ 3) ^ 4
2 * (3 / 4 + 5)
(2 + 3) / (4 -5)
2 / (3 -4) * 5
2 - (3 / (4 - 5) * 6 + 0) ^ 1
(2 - 3 * 4) / (5 * 6 ^ 0) * 1 + 8
I need to produce the output file named “p4out.txt” similar to the following:
Here is the output sample p4out.txt
Symbol Table
Variable Value
a 2
b 3
c 4
d 5
e 6
f 0
g 1
h 8
Input Infix Postfix Result
2 + 3 a+b ab+ 5
(2+ 3) * 4 (a+b)*c ab+c* 20
2 * 3 / (4 -5) all value Omitted downhere
2 / 3 + (4 -5)
2 / 3 + c -d
2 ^ 3 ^ 4
(2 ^ 3) ^ 4
2 * (3 / 4 + 5)
(2 + 3) / (4 -5)
2 / (3 -4) * 5
2 - (3 / (4 - 5) * 6 + 0) ^ 1
(2 - 3 * 4) / (5 * 6 ^ 0) * 1 + 8
Required programs:
ArrayStack.java:
LinkedStack.java:
Postfix.java:
StackInterface.java:
Driver.java:
Explanation / Answer
Below are the details of modifications done:
Postfix.java
/**
* A class that represents a postfix expression. Based on pseudocode in Segments
* 5.16 and 5.18.
*
* @author Frank M. Carrano
* @author Timothy M. Henry
* @version 4.0
*/
public class Postfix {
/**
* Creates a postfix expression that represents a given infix expression.
* Segment 5.16.
*
* @param infix
* A string that is a valid infix expression.
* @return A string that is the postfix expression equivalent to infix.
*/
public static String convertToPostfix(String infix) {
StackInterface<Character> operatorStack = new LinkedStack<Character>();
StringBuilder postfix = new StringBuilder();
int characterCount = infix.length();
char topOperator;
for (int index = 0; index < characterCount; index++) {
boolean done = false;
char nextCharacter = infix.charAt(index);
if (isVariable(nextCharacter))
postfix = postfix.append(nextCharacter);
else {
switch (nextCharacter) {
case '^':
operatorStack.push(nextCharacter);
break;
case '+':
case '-':
case '*':
case '/':
while (!done && !operatorStack.isEmpty()) {
topOperator = operatorStack.peek();
if (getPrecedence(nextCharacter) <= getPrecedence(topOperator)) {
postfix = postfix.append(topOperator);
operatorStack.pop();
} else
done = true;
} // end while
operatorStack.push(nextCharacter);
break;
case '(':
operatorStack.push(nextCharacter);
break;
case ')': // Stack is not empty if infix expression is valid
topOperator = operatorStack.pop();
while (topOperator != '(') {
postfix = postfix.append(topOperator);
topOperator = operatorStack.pop();
} // end while
break;
default:
break; // Ignore unexpected characters
} // end switch
} // end if
} // end for
while (!operatorStack.isEmpty()) {
topOperator = operatorStack.pop();
postfix = postfix.append(topOperator);
} // end while
return postfix.toString();
} // end convertToPostfix
// Indicates the precedence of a given operator.
// Precondition: operator is a character that is (, ), +, -, *, /, or ^.
// Returns an integer that indicates the precedence of operator:
// 0 if ( or ), 1 if + or -, 2 if * or /, 3 if ^,
// -1 if anything else. */
private static int getPrecedence(char operator) {
switch (operator) {
case '(':
case ')':
return 0;
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
} // end switch
return -1;
} // end getPrecedence
private static boolean isVariable(char character) {
return Character.isLetter(character);
} // end isVariable
/**
* Evaluates a postfix expression. Segment 5.18
*
* @param postfix
* a string that is a valid postfix expression.
* @return the value of the postfix expression.
*/
public static double evaluatePostfix(String postfix) {
StackInterface<Double> valueStack = new LinkedStack<Double>();
int characterCount = postfix.length();
for (int index = 0; index < characterCount; index++) {
char nextCharacter = postfix.charAt(index);
switch (nextCharacter) {
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z':
valueStack.push(ValueHandler.valueOf(nextCharacter));
break;
case '+':
case '-':
case '*':
case '/':
case '^':
Double operandTwo = valueStack.pop();
Double operandOne = valueStack.pop();
Double result = compute(operandOne, operandTwo, nextCharacter);
valueStack.push(result);
break;
default:
break; // Ignore unexpected characters
} // end switch
} // end for
return (valueStack.peek()).doubleValue();
} // end evaluatePostfix
private static Double compute(Double operandOne, Double operandTwo,
char operator) {
double result;
switch (operator) {
case '+':
result = operandOne.doubleValue() + operandTwo.doubleValue();
break;
case '-':
result = operandOne.doubleValue() - operandTwo.doubleValue();
break;
case '*':
result = operandOne.doubleValue() * operandTwo.doubleValue();
break;
case '/':
result = operandOne.doubleValue() / operandTwo.doubleValue();
break;
case '^':
result = Math.pow(operandOne.doubleValue(),
operandTwo.doubleValue());
break;
default: // Unexpected character
result = 0;
break;
} // end switch
return result;
} // end compute
} // end Postfix
Driver.java
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/**
A driver that demonstrates the class Postfix.
@author Frank M. Carrano
@author Timothy M. Henry
@version 4.1
*/
public class Driver
{
public static void main(String[] args)
{
try {
BufferedReader bf = new BufferedReader(new FileReader("p4in.txt"));
String line = null;
while((line = bf.readLine()) != null){ //read from input file
String exp = ValueHandler.convertToSymbolExp(line); //Convert values to symbols and write symbol file
testPostfix(exp); //print postfix expression
System.out.println("Evaluated: " + Postfix.evaluatePostfix(Postfix.convertToPostfix(exp)) + " "); //Print evaluated result
}
bf.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} // end main
public static void testPostfix(String infixExpression)
{
System.out.println("Infix: " + infixExpression);
String postfixExpression = Postfix.convertToPostfix(infixExpression);
System.out.println("Postfix: " + postfixExpression);
} // end testPostfix
} // end Driver
ValueHandler.java
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class ValueHandler {
static char nextChar = 'a';
static Map<Double, Character> symbolMap = new HashMap<Double, Character>();
static Map<Character,Double> valueMap = new HashMap<Character, Double>();
public static String convertToSymbolExp(String exp) {
String[] values = exp.split("\+|-|/|\*|\^|\(|\)"); //Get values by avoiding symbols
for (String value : values) {
if (!value.trim().isEmpty()) {
try{
Double doubleValue = Double.parseDouble(value.trim()); //Convert to double value
Character symbol = symbolMap.get(doubleValue); //Check if already assigned value
if (symbol == null) {
symbol = nextChar++; //Assign character symbol for the new value
symbolMap.put(doubleValue, symbol); //Save value in map for easy check
valueMap.put(symbol, doubleValue);
addToOutputFile("p4out.txt",symbol, value.trim()); //Write new symbol to ouput file
}
exp = exp
.replaceFirst(value.trim(), Character.toString(symbol));
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
return exp;
}
private static void addToOutputFile(String file,Character symbol,String value) {
try {
BufferedWriter br = new BufferedWriter(new FileWriter(file,true));
br.write(symbol + " " + value + System.lineSeparator()); //write to file
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
static double valueOf(char variable) {
Double value = valueMap.get(variable); //get corresponding value
if (value != null){
return value;
}
return 0; // Unexpected character
} // end valueOf
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.