I am learning stacks right now, I my code compiles find. When I run it, code will not print my debug println’s and the error
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:2760)
at java.util.Arrays.copyOf(Arrays.java:2734)
at java.util.Vector.ensureCapacityHelper(Vector.java:226)
at java.util.Vector.addElement(Vector.java:573)
at java.util.Stack.push(Stack.java:50)
at stacks.main(stacks.java:56)
is displayed.
My code looks like:
import ch03.stacks.*;
import java.util.*;
public class stacks {
public static void main (String []args){
System.out.printf("Enter a math equation in reverse polish notation:\n");
Stack<Double> pemdas = new Stack<Double>();
Scanner input = new Scanner(System.in);
String in = input.next();
double temp1, temp2, resultant = 0;
while(input.hasNext()){
if(in == "+"){
temp1 = pemdas.peek();
pemdas.pop();
temp2 = pemdas.peek();
pemdas.pop();
resultant = temp1 + temp2;
pemdas.push(resultant);
System.out.println(resultant);
}
if(in == "-"){
temp1 = pemdas.peek();
pemdas.pop();
temp2 = pemdas.peek();
pemdas.pop();
resultant = temp1 - temp2;
pemdas.push(resultant);
System.out.println(resultant);
}
if(in == "*"){
temp1 = pemdas.peek();
pemdas.pop();
temp2 = pemdas.peek();
pemdas.pop();
resultant = temp1 * temp2;
pemdas.push(resultant);
System.out.println(resultant);
}
if(in == "/"){
temp1 = pemdas.peek();
pemdas.pop();
temp2 = pemdas.peek();
pemdas.pop();
resultant = temp1 / temp2;
pemdas.push(resultant);
System.out.println(resultant);
}
else
pemdas.push(Double.parseDouble(in));
System.out.println(resultant);
}
System.out.println("Answer:"+ resultant);
}
}
So i first read in the the string of integers in Reverse Polish Notation and then if it is not an operatand, then i pop it on to my stack. At least that’s what I think it is doing. Any help is greatly appreciated.
You are using Scanner hasNext/next incorrectly. You should always precede each
next()with ahasNext().In your code, you are calling
next()in front of the while loop. Then you are using the return value ofhasNext()to terminate the the while loop. But … you are never calling ‘next()’ within the while loop. ThereforehasNext()always returns true and you are in an infinite loop. This – combined with the peek issue described earlier – may be growing your stack until you run out of memory.The fix is simple. Move
next()right afterhasNext()within the while loopUnfortunately the program still does not work because you are not doing string compares correctly. Replace lines like:
with
Hopefully this was just a typo. If you don’t understand why using == for string compares is a problem, you will need to review Java equality.
Finally, there is a problem with your if logic. Hint: to handle mutually exclusive cases, use code like: