Question
Java Programming: Using the dictionary class I wrote in class the other day, modify your infix expression evaluator so that it can use variables.(@CHEGG EXPERT:THIS
Java Programming:
Using the dictionary class I wrote in class the other day, modify your infix expression evaluator so that it can use variables.(@CHEGG EXPERT:THIS PART IS DONE)
Create a dictionary. Add some variable names and associated values to it, then modify your evaluator so that the text string can include the names of variables as well as constants. When you encounter a variable name, look it up in the dictionary and use the value you find there. Treat undefined variables as an error.(@CHEGG EXPERT: THIS PART IS DONE) (@CHEGG EXPERT: DO THE STUFF BELOW)
Finally, modify your text editor from a previous lab to add the instruction LET to its vocabulary. The syntax for LET should be LET = The result should be to evaluate the expression and assign its value to the variable on the left hand side of the -. So, the following sequence of events: LET A = 10 LET B = 20 LET C = (A + B) / 2.0 should result in C having the associated value 15.0 Add a PRINT command which will print the contents of a variable: PRINT C should give 15.0 in the above example
Modify the classes below to do so
Evaluator Class
import java.util.*;
public class EvaluateExpression {
private static Dictionary variables; public static double solveExpression(String expression) { char[] tokens = expression.toCharArray(); // make sure you delete all the white spaces //Number Stack Stack valueStack = new Stack<>(); //Operator Stack Stack opsStack = new Stack<>(); for (int i = 0; i < tokens.length; i++) { if(tokens[i] == ' ') continue; // if current character is a space, ignore it if ( Character.isDigit(tokens[i])) { // if current character is a digit, then StringBuilder sbuf = new StringBuilder(); // string builder is more faster than StringBuffer while (i < tokens.length && (Character.isDigit(tokens[i]) || (tokens[i] == '.'))) { sbuf.append(tokens[i++]); } valueStack.push(Double.parseDouble(sbuf.toString())); } else if (tokens[i] == '(') { opsStack.push(tokens[i]); } else if (tokens[i] == ')') { while (opsStack.peek() != '(') { valueStack.push(performOperation(opsStack.pop(), valueStack.pop(), valueStack.pop())); } opsStack.pop(); } else if (isOperator(tokens[i])) { // if current character is an operator, then while (!opsStack.empty() && isPrecedence(tokens[i], opsStack.peek())) { valueStack.push(performOperation(opsStack.pop(), valueStack.pop(), valueStack.pop())); } opsStack.push(tokens[i]); } else { // if it is neither a digit nor a operator, it might be a variable try { StringBuilder sbuf = new StringBuilder(); // string builder is more faster than StringBuffer while (i < tokens.length && (Character.isAlphabetic(tokens[i]))) { // read all the characters of variable sbuf.append(tokens[i++]); // read the characters of the variable } String varialbe = sbuf.toString(); // get the name of the variable double val = variables.lookup(varialbe); // get the value of the expression
valueStack.push(val); } catch (HashException | NullPointerException ex) { // we get exception when the dictionary doesnt have the variable we wanted // then it is an invalid expression System.out.println("Invalid Expression : "+tokens[i]); } } } while (!opsStack.empty()) { valueStack.push(performOperation(opsStack.pop(), valueStack.pop(), valueStack.pop())); } return valueStack.pop(); }
public static boolean isPrecedence(char op1, char op2) { if (op2 == '(' || op2 == ')') { return false; } return !((op1 == '/' || op1 == '*') && (op2 == '-' || op2 == '+')); } public static double performOperation(char op, double a, double b) { switch (op) { case '+': return b + a; case '-': return b - a; case '*': return b * a; case '/': if (a == 0) { throw new UnsupportedOperationException("Cannot divide by zero"); } return b / a; } return 0.0; }
private static boolean isOperator(char c) { // return true if c is an operator return c == '+' || c == '-' || c == '*' || c == '/'; } public static void main(String[] args) throws HashException { // System.out.println("10.0 + 3 * 45.0 = " + EvaluateExpression.solveExpression("10.0 + 3 * 45.0")); // System.out.println("100 * ( 2 + 12 ) = " + EvaluateExpression.solveExpression("100 * ( 2 + 12 )")); // System.out.println("100 * ( 2 + 12 ) / 14 = " + EvaluateExpression.solveExpression("100 * ( 2 + 12 ) / 14")); // Create a dictionary of variables a, b, c, and d variables = new Dictionary(5); variables.insert("anu", 10); variables.insert("b", 17); variables.insert("c", 20); variables.insert("d", 13); String expression = "anu * b + ( c / anu ) - d"; System.out.println(expression+" = "+EvaluateExpression.solveExpression(expression)); expression = "10 * 17 + ( 20 / 10 ) - 13"; System.out.println(expression+" = "+EvaluateExpression.solveExpression(expression)); } }
Dictionary Class
public class Dictionary { private final HashClass theDict[]; private final int size; private int used;
public Dictionary(int maxSize) { this.theDict = new HashClass[maxSize]; this.size = maxSize; this.used = 0; } private int hash(String s) { int retval = 0; for(int i = 0; i < s.length(); i++) { retval += (int)s.charAt(i); } return retval % size; } public boolean isFull() { return used >= size-1; } private int findWhere(String s) {// finds s or where it should be
int where = this.hash(s); while (theDict[where] != null && !theDict[where].getKey().equals(s)) { //System.out.println("Ouch"); where = (where + 1) % size; } return where; }
public void delete(String s) throws HashException { int where = findWhere(s); if(theDict[where] != null) { theDict[where] = null; used--; } else { throw new HashException("Missing Key" + s); } }
public double lookup(String s) throws HashException { int where = findWhere(s); if(theDict[where] != null) return theDict[where].getValue(); else throw new HashException("Missing Key" + s); }
public void insert(String s, double val) throws HashException { if(this.isFull()) { throw new HashException("Hash table overflow"); } int where = findWhere(s); if (theDict[where] == null) { theDict[where] = new HashClass(s, val); used++; } else theDict[where].setValue(val); }
@Override public String toString() { String retval = ""; for(int i = 0; i < size; i++) { if (theDict[i] != null) retval += i + " " + theDict[i] + " "; } return retval; }
public static void main(String args[]) throws Exception { String words[] = {"cow", "aardvark", "axolotl", "hardware", "software", "tick", "waterbug", "tiger", "caribou", "dog", "clavicle", "patella", "appendix", "liver", "gizzard"}; Dictionary dict = new Dictionary(10); for(int i = 0; i < words.length; i++) { dict.insert(words[i], i*2.5); } System.out.println(dict); } }
Hash Class:
public class HashClass { private String key; private double value;
public HashClass(String key, double value) { this.key = key; this.value = value; }
public String getKey() { return key; }
public void setKey(String key) { this.key = key; }
public double getValue() { return value; }
public void setValue(double value) { this.value = value; }
}
Hash Exception class:
public class HashException extends Exception { HashException(String string) { super(string); } }
Editor Class:
import java.util.Scanner; import java.util.StringTokenizer; import java.io.*; public class Editor { private LLComp theText; private String prompt;
static BufferedWriter bw = null; static BufferedReader br = null;
private enum Keywords { READ, SAVE, LIST, RESEQUENCE, QUIT, EXIT, UNDEFINED; };
private Scanner console;
public Editor() { this.theText = new LLComp(); this.prompt = ">"; this.console = new Scanner(System.in); }
public String getPrompt() { return ""; }
public void setPrompt(String p) { }
private static boolean isInt(String s) // see if a string represents { // an integer. boolean retval = false; try { Integer.parseInt(s); retval = true; } catch (NumberFormatException e) { retval = false; } return retval; }
public void process() { boolean done = false; String line; while (!done) { System.out.print(this.prompt); line = console.nextLine().toUpperCase(); // Work only with upper case String splitString[] = line.split(" ", 2); // at this point, the line that was read in has been split into two // arrays. splitString[0] contains the first token, splitString[1] // contains all the rest of the line.
// At this point, you need to decide whether this is a command or // a line of text to be entered. if (this.isInt(splitString[0])) { // Here we have a line of text to be entered. Write the code to // insert it into the LLComp named theText. theText.insertInOrder(line); } else // otherwise, it is a command, so call doCommand to perform it. done = this.doCommand(splitString[0]); } }
private boolean doCommand(String com) { boolean retval = false; Keywords command; // This first bit takes the string in the first word of the line // and turns it into one of the manifest constants of the // enumerated data type. This makes it fairly easy to add new // commands later. try { command = Keywords.valueOf(com);// command is a Keywords and can } // can be used as the target of a switch. catch (IllegalArgumentException e) { command = Keywords.UNDEFINED; // An undefined Keywords will cause } // an exception. switch (command) { case READ: this.read(); break; case SAVE: this.save(); break; case LIST: this.list(); break; case RESEQUENCE: this.resequence(); break; case QUIT: System.exit(0); break; case EXIT: retval = true; break; case UNDEFINED: System.out.println("Undefined command:" + com); } return retval; }
// You need to implement the following routines.
private void read() { String textLine; try { while((textLine = br.readLine())!=null) System.out.println(textLine); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
private void save() { try { bw.write(theText.toString()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { bw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
private void list() { System.out.println(theText); }
private void resequence() { String text = theText.toString(); String[] textL = text.split(" "); System.out.println("Number of Lines" + textL.length); if(textL.length < 10) System.out.println("There is not more than 10 records"); else { for(int i = 9;i { String[] stringText = textL[i].split(" " ); int number = Integer.parseInt(stringText[0]) + 10; System.out.println(number +" " + stringText[1]); } } }
public static void main(String args[]) { Editor e = new Editor(); try { bw = new BufferedWriter(new FileWriter("ProgramOutput.txt")); br = new BufferedReader(new FileReader("ProgramOutput.txt")); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } e.process(); } }
LL Comp (for Editor):
public class LLComp> { private CListElement head; private CListElement tail;
public LLComp() { this.head = new CListElement(); this.tail = this.head; }
public void insertInOrder(T val) { recInsInOrder(head, val); }
private void recInsInOrder(CListElement head, T val) { if (head.link == null) { head.link = new CListElement(val); } else { if (head.link.value.compareTo(val) > 0) { head.link = new CListElement(val, head.link); } else { recInsInOrder(head.link, val); } } } public void insertHead(T val) { this.head.link = new CListElement(val, this.head.link); }
public void insertTail(T val) { this.tail.link = new CListElement(val); this.tail = this.tail.link; }
public boolean isEmpty() { return this.head.link == null; }
public T deleteHead() throws LLException { T retval = null; if (this.isEmpty() ) throw new LLException("Attempt to delete from an empty list."); else { retval = (T)this.head.link.value; this.head.link = this.head.link.link; if (this.isEmpty()) this.tail = this.head; } return retval; } public String toString() { String retval = ""; CListElement where = this.head;
while (where.link != null) { retval += where.link.value + " "; where = where.link; } return retval; }
public static void main(String args[]) { LLComp myLL = new LLComp();
myLL.insertInOrder("xyzzy"); myLL.insertInOrder("lmnop"); myLL.insertInOrder("nope"); myLL.insertInOrder("zzzzz");
System.out.println(myLL); }
} class CListElement { R value; CListElement link;
public CListElement(R v, CListElement le) { this.value = v; this.link = le; }
public CListElement(R v) { this(v, null); }
public CListElement() { this(null, null); } }
LL Exception:
public class LLException extends Exception { public LLException(String s) { super(s); }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started