Complete the class Search in Java which uses the Visitor pattern that counts the
ID: 3867263 • Letter: C
Question
Complete the class Search in Java which uses the Visitor pattern that counts the number of occurrences of a given literal value in the expression. How many times does 2 occur in the expression 2*3+2*2+2? Answer: 2 occurs four times
public class Search implements IVisitor {
private String searchArgument;
public Search(String arg){
searchArgument = arg;
}
@Override
public Object visit(Expression node) {
double count;
if (node.operand.equals(searchArgument))
count =1.0;
else
count =0.0;
return ((double)node.left.visit(this)) + ((double)node.right.visit(this)) + count;
}
@Override
public Object visit(Literal node) {
// complete this method
return 0.0;
}
@Override
public Object visit(Variable node) {
// compelte this method
return 0.0;
}
}
-------------------------------------------------------------------------------------------------------------------------------
Literal Class:
public class Literal implements INode {
double value;
public Literal(double value) {
this.value = value;
}
public Object visit(IVisitor visitor) {
return visitor.visit(this);
}
}
Variable Class:
public class Variable implements INode {
String name;
public Variable(String name) {
this.name = name;
}
public Object visit(IVisitor visitor) {
return visitor.visit(this);
}
}
Explanation / Answer
public class Search implements IVisitor {
private String searchArgument;
public Search(String arg){
searchArgument = arg;
}
@Override
public Object visit(Expression node) {
double count;
if (node.operand.equals(searchArgument))
count =1.0;
else
count =0.0;
return ((double)node.left.visit(this)) + ((double)node.right.visit(this)) + count;
}
@Override
public Object visit(Literal node) {
// complete this method
double count;
// Convert the given search argument literal value into double
// and compare with the value of the literal at the node
double searchValue = Double.parseDouble(searchArgument);
// return 1 if the search argument matches with the value at the node
if (node.value == searchValue)
count = 1.0;
else
count = 0.0;
return count;
}
@Override
public Object visit(Variable node) {
// complete this method
double count;
// compare the name of the variable at the node with the search argument
// return 1 if the search argument matches with the variable name at the node
if (node.name.equals(searchArgument))
count = 1.0;
else
count = 0.0;
return count;
}
}