Rules of implementation!:
Note that the java.io.*, java.util.*, and java.util.regex.* import statements at the top of the file allow for using ANY class in java.io, java.util, and java.util.regex without additional specification or qualification.
Guidelines and recommendations for implementing evaluate
While recursion is optional for this assignment, using it to evaluate subexpressions will make it a LOT easier to write working code. (This is a great opportunity to learn how to use recursion in a realistic situation!!)
There are a couple of coding options if you want to use recursion:
So, for instance, if the main expression is
a-(b+A[B[2]])*d+3
01234567891111111 (these are the positions of the characters in the expression)
0123456
then, to recursively evaluate the subexpression in parentheses, you
may call the recursive evaluate method like this:
float res = evaluate(expr.substring(3,11), vars, arrays);
float res = evaluate(expr, 3, 11, vars, arrays);(The expr parameter is the original expression for every call.)
And, to start with, you may call the recursive evaluate method from the public evaluate method like this:
return evaluate(expr, 0, expr.length()-1, vars, arrays);which is the entire expression.
You will need to use this second option if you want to include other parameters in your recursive evaluate.
________________________________________________
HERE ARE THE CLASSES:
package app;
/**
* This class holds a (name, integer value) pair for a simple (non-array) variable.
* The variable name is a sequence of one or more letters.
*
*
*/
public class Variable {
/**
* Name, sequence of letters
*/
public String name;
/**
* Integer value
*/
public int value;
/**
* Initializes with name, and zero value
*
* @param name Variable name
*/
public Variable(String name) {
this.name = name;
value = 0;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString() {
return name + "=" + value;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object o) {
if (o == null || !(o instanceof Variable)) {
return false;
}
Variable ss = (Variable)o;
return name.equals(ss.name);
}
}
______________________________________
package app;
/**
* This class holds a (name, array of integer values) pair for an array.
* The name is a sequence of one or more letters.
*
*
*/
public class Array {
/**
* Name, sequence of letters
*/
public String name;
/**
* Array of integer values
*/
public int[] values;
/**
* Initializes with name, and sets values to null.
*
* @param name Name of array
*/
public Array(String name) {
this.name = name;
values = null;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString() {
if (values == null || values.length == 0) {
return name + "=[ ]";
}
StringBuilder sb = new StringBuilder();
sb.append(name);
sb.append("=[");
sb.append(values[0]);
for (int i=1; i < values.length; i++) {
sb.append(',');
sb.append(values[i]);
}
sb.append(']');
return sb.toString();
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object o) {
if (o == null || !(o instanceof Array)) {
return false;
}
Array as = (Array)o;
return name.equals(as.name);
}
}
________________________
package app;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class Evaluator {
/**
* @param args
*/
public static void main(String[] args) throws
IOException {
Scanner sc = new
Scanner(System.in);
while (true) {
System.out.print("\nEnter the expression, or hit return to quit
=> ");
String expr =
sc.nextLine();
if
(expr.length() == 0) {
break;
}
ArrayList<Variable> vars = new ArrayList<>();
ArrayList<Array> arrays = new ArrayList<>();
Expression.makeVariableLists(expr, vars, arrays);
System.out.print("Enter variable values file name, or hit return if
no variables => ");
String fname =
sc.nextLine();
if
(fname.length() != 0) {
Scanner scfile = new Scanner(new
File(fname));
Expression.loadVariableValues(scfile, vars,
arrays);
}
System.out.println("Value of expression = " +
Expression.evaluate(expr,vars,arrays));
}
sc.close();
}
}
____________________________
THIS IS THE CLASS WHICH YOU WILL BE WORKING ON:
package app;
import java.io.*;
import java.util.*;
import java.util.regex.*;
import structures.Stack;
public class Expression {
public static String delims = " \t*+-/()[]";
public static void
makeVariableLists(String expr, ArrayList<Variable> vars,
ArrayList<Array> arrays) {
/** COMPLETE THIS METHOD **/
/** DO NOT create new vars and arrays - they are
already created before being sent in
** to this method - you just need to fill them
in.
**/
}
public static void
loadVariableValues(Scanner sc, ArrayList<Variable> vars,
ArrayList<Array> arrays)
throws IOException {
while (sc.hasNextLine()) {
StringTokenizer st = new
StringTokenizer(sc.nextLine().trim());
int numTokens = st.countTokens();
String tok = st.nextToken();
Variable var = new Variable(tok);
Array arr = new Array(tok);
int vari = vars.indexOf(var);
int arri = arrays.indexOf(arr);
if (vari == -1 && arri == -1) {
continue;
}
int num = Integer.parseInt(st.nextToken());
if (numTokens == 2) { // scalar symbol
vars.get(vari).value = num;
} else { // array symbol
arr = arrays.get(arri);
arr.values = new int[num];
// following are (index,val) pairs
while (st.hasMoreTokens()) {
tok = st.nextToken();
StringTokenizer stt = new StringTokenizer(tok," (,)");
int index = Integer.parseInt(stt.nextToken());
int val = Integer.parseInt(stt.nextToken());
arr.values[index] = val;
}
}
}
}
public static float
evaluate(String expr, ArrayList<Variable> vars,
ArrayList<Array> arrays) {
/** COMPLETE THIS METHOD **/
// following line just a placeholder for
compilation
return 0;
}
}
__________________________________
Here are some sample expressions of the kind your program will evaluate:
3 Xyz 3-4*5 a-(b+A[B[2]])*d+3 A[2*(a+b)] (varx + vary*varz[(vara+varb[(a+b)*33])])/55
WILL GIVE THUMBS UP FOR GOOD WORK. PLEASE FOLLOW THE GUIDELINE. THANK YOU.
Please let me know if you have any doubts or you want me to modify the answer. And if you find this answer useful then don't forget to rate my answer as thumps up. Thank you! :)
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class Evaluator {
public static void main(String[] args) throws
IOException {
Scanner sc = new
Scanner(System.in);
while (true) {
System.out.print("\nEnter the expression, or hit return to quit
=> ");
String expression = sc.nextLine();
if (expression.length() == 0) {
break;
}
ArrayList<Variable> variable = new ArrayList<>();
ArrayList<Array> arrays = new ArrayList<>();
Expression.makeVariableList(expression, variable, arrays);
System.out.print("Enter variable values file name, or hit return if
no variables => ");
String fname = sc.nextLine();
if (fname.length() != 0) {
Scanner sourcefile = new Scanner(new
File("/Users/swapnil/IdeaProjects/ExpressionEvaluatorRecursion/src/input.txt"));
Expression.loadVariableValues(sourcefile, variable, arrays);
}
System.out.println("Value of expression = " +
Expression.evaluate(expression,variable,arrays));
}
sc.close();
}
}
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
public class Array {
public String name;
public int[] values;
public Array(String name) {
this.name = name;
values = null;
}
public String toString() {
if (values == null ||
values.length == 0) {
return name + "=[ ]";
}
StringBuilder sb = new
StringBuilder();
sb.append(name);
sb.append("=[");
sb.append(values[0]);
for (int i = 1; i <
values.length; i++) {
sb.append(',');
sb.append(values[i]);
}
sb.append(']');
return
sb.toString();
}
public boolean equals(Object o) {
if (o == null || !(o
instanceof Array)) {
return false;
}
Array as = (Array)
o;
return
name.equals(as.name);
}
}
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
public class Variable {
public String name;
public int value;
public Variable(String name) {
this.name = name;
value = 0;
}
public String toString() {
return name + "=" +
value;
}
public boolean equals(Object o) {
if (o == null || !(o
instanceof Variable)) {
return false;
}
Variable ss =
(Variable)o;
return
name.equals(ss.name);
}
}
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
import java.io.*;
import java.util.*;
public class Expression {
public static String delims = " \t*+-/()[]";
private static boolean
arrayExist(ArrayList<Array> arrays, String name) {
for(int j = 0; j <
arrays.size(); j++) {
if(arrays.get(j).name.equals(name)) {
return true;
}
}
return false;
}
private static boolean
variableExist(ArrayList<Variable> variables, String name)
{
for(int j = 0; j <
variables.size(); j++) {
if(variables.get(j).name.equals(name)) {
return true;
}
}
return false;
}
public static void makeVariableList(String
expression, ArrayList<Variable> variable,
ArrayList<Array> arrays) {
String
current_name;
expression =
expression.trim();
char expressionTokens []
= expression.toCharArray();
loop:
for(int i = 0; i <
expression.length(); i ++) {
char current = expressionTokens[i];
if(Character.isLetter(current)) {
switch(current) {
case 'v':
case 'V':
if(expressionTokens.length > i+2) {
if(expressionTokens[i+1] == 'a' && expressionTokens[i+2] ==
'r') {
int end = i;
while(Character.isLetter(expressionTokens[end]) && end <
expressionTokens.length-1) {
end++;
}
if(end == expressionTokens.length-1 &&
Character.isLetter(expressionTokens[end])) {
current_name = expression.substring(i, end+1);
} else {
current_name = expression.substring(i, end);
}
if(expressionTokens[end] == '[') {
if(!arrayExist(arrays, current_name)) {
arrays.add(new Array(current_name));
}
i = end;
continue loop;
}
if(!variableExist(variable, current_name)) {
variable.add(new Variable(current_name));
}
i = end;
continue loop;
}
}
int end = i;
while(Character.isLetter(expressionTokens[end]) && end <
expressionTokens.length-1) {
end++;
}
if(end == expressionTokens.length-1 &&
Character.isLetter(expressionTokens[end])) {
current_name = expression.substring(i, end+1);
} else {
current_name = expression.substring(i, end);
}
if(expressionTokens[end] == '[') {
if(!arrayExist(arrays, current_name)) {
arrays.add(new Array(current_name));
}
i = end;
continue loop;
}
if(!variableExist(variable, current_name)) {
variable.add(new Variable(current_name));
}
i = end;
continue loop;
default:
end = i;
while(Character.isLetter(expressionTokens[end]) && end <
expressionTokens.length-1) {
end++;
}
if(end == expressionTokens.length-1 &&
Character.isLetter(expressionTokens[end])) {
current_name = expression.substring(i, end+1);
} else {
current_name = expression.substring(i, end);
}
if(expressionTokens[end] == '[') {
if(!arrayExist(arrays, current_name)) {
arrays.add(new Array(current_name));
}
i = end;
continue loop;
}
if(!variableExist(variable, current_name)) {
variable.add(new Variable(current_name));
}
i = end;
continue loop;
}
}
}
}
public static void
loadVariableValues(Scanner sc,
ArrayList<Variable> variable, ArrayList<Array>
arrays)
throws IOException {
while (sc.hasNextLine())
{
StringTokenizer st = new
StringTokenizer(sc.nextLine().trim());
int numTokens = st.countTokens();
String tok = st.nextToken();
Variable var = new Variable(tok);
Array arr = new Array(tok);
int vari = variable.indexOf(var);
int arri = arrays.indexOf(arr);
if (vari == -1 && arri == -1) {
continue;
}
int num = Integer.parseInt(st.nextToken());
if (numTokens == 2) {
variable.get(vari).value = num;
} else {
arr = arrays.get(arri);
arr.values = new int[num];
while (st.hasMoreTokens()) {
tok = st.nextToken();
StringTokenizer stt = new StringTokenizer(tok," (,)");
int index = Integer.parseInt(stt.nextToken());
int val = Integer.parseInt(stt.nextToken());
arr.values[index] = val;
}
}
}
}
private static int
getVarVal(ArrayList<Variable> variable, String name) {
int i = 0;
while(!variable.get(i).name.equals(name)) {
i++;
}
return
variable.get(i).value;
}
private static int
getArrVal(ArrayList<Array> arrays, String name, int index)
{
int i = 0;
while(!arrays.get(i).name.equals(name)) {
i++;
}
return
arrays.get(i).values[index];
}
private static boolean isPrecedent(char
currOperator, char nextOperator) {
if((currOperator == '*'
|| currOperator == '/') && (nextOperator == '-' ||
nextOperator == '+')) {
return false;
}
if((nextOperator ==')'
|| nextOperator == '(')){
return false;
}
return true;
}
private static float operate(float b, float a,
char currentOperator) {
float value = 0;
switch(currentOperator)
{
case '*':
value = (a*b);
break;
case '/':
value = (a/b);
break;
case '+':
value = (a+b);
break;
case '-':
value = (a-b);
}
return value;
}
public static float evaluate(String expr,
ArrayList<Variable> variable, ArrayList<Array> arrays)
{
if(expr.isEmpty())
{
return 0;
}
Stack<Float>
numberStack = new Stack<Float>();
Stack<Character>
operatorStack = new Stack<Character>();
String
current_name;
int end = 0;
expr =
expr.trim();
String [] exprTokens =
expr.split("");
loop:
for(int i = 0; i <
exprTokens.length; i++) {
char current = exprTokens[i].charAt(0);
if(Character.isDigit(current)){
end = i;
while(Character.isDigit(exprTokens[end].charAt(0)) && end
< exprTokens.length-1) {
end++;
}
if(end == exprTokens.length-1 &&
Character.isDigit(exprTokens[end].charAt(0))) {
end = end+1;
}
numberStack.push((float) Long.parseLong(expr.substring(i,
end)));
i = end-1;
continue loop;
} else if(Character.isLetter(current)) {
end = i;
while(Character.isLetter(exprTokens[end].charAt(0)) && end
< exprTokens.length-1) {
end++;
}
if(end == exprTokens.length-1 &&
Character.isLetter(exprTokens[end].charAt(0))) {
current_name = expr.substring(i, end+1);
} else {
current_name = expr.substring(i, end);
}
if(variableExist(variable, current_name)) {
numberStack.push((float) getVarVal(variable, current_name));
if(end == exprTokens.length-1) {
i = end;
} else {
i = end-1;
}
continue loop;
}
i = end+1;
end = i;
int nests = 1;
int endNests = 0;
while(nests > endNests) {
if(exprTokens[end].charAt(0) == '[') {
nests++;
} else if(exprTokens[end].charAt(0)== ']') {
endNests++;
if(endNests == nests) {
break;
}
}
end++;
}
float index = evaluate(expr.substring(i, end),variable,
arrays);
numberStack.push((float) getArrVal(arrays, current_name, (int)
index));
i = end;
continue loop;
} else {
switch(current) {
case '(':
i = i+1;
end = i;
int nests = 1;
int endNests = 0;
while(nests > endNests) {
if(exprTokens[end].charAt(0) == '(') {
nests++;
} else if(exprTokens[end].charAt(0) == ')') {
endNests++;
if(endNests == nests) {
break;
}
}
end++;
}
numberStack.push(evaluate(expr.substring(i, end), variable,
arrays));
i = end;
continue loop;
case ' ':
continue loop;
default:
while(!operatorStack.isEmpty() && isPrecedent(current,
operatorStack.peek())) {
numberStack.push(operate(numberStack.pop(), numberStack.pop(),
operatorStack.pop()));
}
operatorStack.push(current);
}
}
}
while(!operatorStack.isEmpty()) {
numberStack.push(operate(numberStack.pop(), numberStack.pop(),
operatorStack.pop()));
}
return
numberStack.pop();
}
}
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
//input.txt
a 3
b 2
A 5 (2,3) (4,5)
B 3 (2,1)
d 56

Rules of implementation!: You may NOT modify any of the files except Expression.java in ANY way....
Programming Assignment #7 (Recursion) This assignment is to write some methods that perform simple array operations recursively. Specifically, you will write the bodies for the recursive methods of the ArrayRecursion class, available on the class web page. No credit will be given if any changes are made to ArrayRecursion.java, other than completing the method bodies Note that the public methods of ArrayRecursion – contains(), getIndexOfSmallest(), and sort() – cannot be recursive because they have no parameters. Each of these methods...
In Java: Executable Class create an array of Employee objects. You can copy the array you made for Chapter 20. create an ArrayList of Employee objects from that array. use an enhanced for loop to print all employees as shown in the sample output. create a TreeMap that uses Strings for keys and Employees as values. this TreeMap should map Employee ID numbers to their associated Employees. process the ArrayList to add elements to this map. print all employees in...
How to solve and code the following requirements (below) using the JAVA program? 1. Modify the FoodProduct Class to implement Edible, add the @Overrride before any methods that were there (get/set methods) that are also in the Edible interface. 2. Modify the CleaningProduct Class to implement Chemical, add the @Overrride before any methods that were there (get/set methods) that are also in the Chemical interface. 3. Create main class to read products from a file, instantiate them, load them into...
The names of the two input files as well as the output file are supposed to be provided as arguments. Could you please fix it? Thanks. DPriorityQueue.java: // Import the required classes import java.io.*; import java.util.*; //Create the class public class DPriorityQueue { //Declare the private members variables. private int type1,type2; private String CostInTime[][], SVertex, DVertex; private List<String> listOfTheNodes; private Set<String> List; private List<Root> ListOfVisitedNode; private HashMap<String, Integer> minimalDistance; private HashMap<String, Integer> distOfVertices; private PriorityQueue<City> priorityQueue; // prove the definition...
Must be written in JAVA Code Modify Fig. 19.2 to use recursive method recursiveLinear-Search to perform a linear search of the array. The method should receive the search key and starting index as arguments. If the search key is found, return its index in the array; otherwise, return –1. Each call to the recursive method should check one index in the array. Figure 19.2 import java.security.SecureRandom; import java.util.Arrays; import java.util.Scanner; public class LinearSearchTest{ public static int linearSearch(int data[], int searchKey)...
A teacher wants to create a list of students in her class. Using the existing Student class in this exercise. Create a static ArrayList called classList that adds a student to the classList whenever a new Student is created. In the constructor, you will have to add that Student to the ArrayList. Coding below was given to edit and use public class ClassListTester { public static void main(String[] args) { //You don't need to change anything here, but feel free...
A teacher wants to create a list of students in her class. Using the existing Student class in this exercise. Create a static ArrayList called classList that adds a student to the classList whenever a new Student is created. In the constructor, you will have to add that Student to the ArrayList. Coding below was given to edit and use public class ClassListTester { public static void main(String[] args) { //You don't need to change anything here, but feel free...
Modify the library program as follows: Create a method in the LibraryMaterial class that accepts a string s as a parameter and returns true if the title of the string is equal to s. Create the same method for your library material copies. Note that it will need to be abstract in the LibraryMaterialCopy class MY CODE **************************************************************** LibraryCard: import java.util.List; import java.util.ArrayList; import java.time.LocalDate; import java.time.temporal.ChronoUnit; public class LibraryCard { private String id; private String cardholderName; ...
Introduction In this lab, you will be working with three classes: Person, Student, and Roster. Person and Student represent individuals with a first and last name as String class variables, and Student has an additional int class variable that represents a ID number. The Roster class represents a group of people that are objects of either the Person or Student class. It contains an ArrayList. The Person class has been completed for you with class variables, a constructor, and a...
I asked this a little bit ago but didn't clarify exactly what I needed, so I'm asking again...I've attached my code below the question. Thanks! Do not change the original contract of the Course class. Instead, ONLY change the implementation of property students, from an array to and ArrayList, and update any methods in class Course that access students to reflect ArrayList. The methods are overridden. That means that you do not need to change the header for methods, only...