Complete the class Search in Java which uses the Visitor pattern that counts the
ID: 3866784 • 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
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);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.