1

I am getting this error when running this code

private static List<Integer> array(int num) {
       List<Integer> value = new ArrayList<>();

        while (num != 1) {
            if(num % 2 == 0) {
             value.add(num + 2);
             }else {
              value.add(num * 3 + 1);
             }
        }
       System.out.println(value);
        return value;
    }

Can i get an explanation of whats wrong ?

valik
  • 2,014
  • 4
  • 24
  • 55
  • 7
    You never modify `num`. – shmosel Nov 02 '18 at 22:06
  • 1
    Possible duplicate of [What is an OutOfMemoryError and how do I debug and fix it](https://stackoverflow.com/questions/24510188/what-is-an-outofmemoryerror-and-how-do-i-debug-and-fix-it) – Joe C Nov 02 '18 at 22:07

2 Answers2

5

You have an infinite loop. Each iteration will add to the List until you run OutOfMemory. You need to change num during the loop in such a way that it becomes 1 at some point so the loop ends.

2

Your while condition never equates to false, so the loop runs endlessly. As shmosie said, you never modify num, so maybe look into modding num, or performing some operation on it so that it actually equals 1 in order for your loop to stop

Taha
  • 65
  • 1
  • 10