Can anyone provide the code based on this pseudocode in Java? I do rate the answ
ID: 3824822 • Letter: C
Question
Can anyone provide the code based on this pseudocode in Java?
I do rate the answer, please answer it as accurate as possible. Thank you!
CSE1 16/504 F16 Midterm #2 Page 2 1)/14 points] 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 earn an automatic 0 AND you will be required to sit in a room and think of all the kittens you made sad. 1 Declare a Stack of Double variable named s 2 Set s equal to a new instance of Stack 3 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 Number Utils. isNumber (val) then num Double parseDouble (val) else if s has fewer than 2 elements then 10 l Throw an Invalid operation Exception exception else double left value returned by method removing an element from s double right value returned by method removing an element from s 13 num left right 15 Add num to s 16 double retval; s 17 retval value returned by method removing an element from 18 return retval public double calculate (Queue String> q)Explanation / Answer
Please note I am using my own method "isNumeric" to check if a string is representing Double as NumberUtils is not part of standard java jdk.
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();
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.