Quantcast
Channel: Why do I get a java.lang.OutOfMemoryError: Java heap space error? - Stack Overflow
Viewing all articles
Browse latest Browse all 3

Answer by Guido Simone for Why do I get a java.lang.OutOfMemoryError: Java heap space error?

$
0
0

You are using Scanner hasNext/next incorrectly. You should always precede each next() with a hasNext().

In your code, you are calling next() in front of the while loop. Then you are using the return value of hasNext() to terminate the the while loop. But ... you are never calling 'next()' within the while loop. Therefore hasNext() 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 after hasNext() within the while loop

Scanner input = new Scanner(System.in);double temp1, temp2, resultant = 0;while(input.hasNext()) {    String in = input.next();

Unfortunately the program still does not work because you are not doing string compares correctly. Replace lines like:

if (in == "+")

with

if (in.equals("+"))

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:

if () {}else if (){}else if (){}else{}

Viewing all articles
Browse latest Browse all 3

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>