Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Hertzlet-Packard (HP for short) makes high-end calculators used by Hertz-speare

ID: 3823976 • Letter: H

Question

Hertzlet-Packard (HP for short) makes high-end calculators used by Hertz-speare scholars, ceramic engineers, and other nerds. Unlike humans, HP users type equations in reverse-polish notation - a highly logical and thoroughly incomprehensible way of writing calculations that eliminates needing parentheses. HP code traditionally used arrays. After many arguments, they have grudginly accepted the benefits of using basic data structures. Complete the calculate method by implementing the given algorithm. This algorithm processes the reverse-polish notation equation in q and returns the value calculated. Using a stack's List methods, while legal Java, will cam an automatic 0 AND you will be required to sit in a room and think of all the kittens you made sad. Declare a Stack of Double variable named a Set a equal to a new instance of Stack while q contains one or more elements do double num; String val; Set val equal to value returned by method removing an element from q if NumbberUtils.isNuBber(val) then num = Double.parseDouble(val) else if s has fewer than 2 elements then Throw an invalldOperationException exception else double left = value returned by method removing an element from s double right = value returned by method removing an element from s num = left + right Add nun to s double ratVal; ratVal = value returned by method removing an element from s return retVal public double calculate(Queue q) {

Explanation / Answer

public static boolean isNumeric(String str)
{
try
{
Double.parseDouble(str);
}
catch(NumberFormatException nfe)
{
return false;
}
return true;
}
  
public double calculate(Queue<String> q) throws Exception
{
Stack<Double> s = new Stack<>();
while(!q.isEmpty())
{
double num;
String val = q.remove();
if(isNumeric(val))
{
num = Double.parseDouble(val);
}
else if(s.size() < 2)
{
throw new Exception("Invalid operation");
}
else
{
double left = s.pop();
double right = s.pop();
num = left+right;
}
s.push(num);
}
return s.pop();
  
}