0
ArrayList<Integer> digitList = new ArrayList<Integer>();
ArrayList<Integer> newBase = new ArrayList<Integer>();

public void toX(int base, int oNum) {
    while(base > 0) {
        digitList.add(base % 10);
        base /= 10;
    }
    int[] digits = digitList.stream().mapToInt(i->i).toArray();
    for(int i = 0; i<digits.length/2; i++) {
        int a = digits[i];
        digits[i] = digits[digits.length -i -1];
        digits[digits.length -i -1] = a;
    }
    System.out.println(Arrays.toString(digits));
    for(int i = 0; i < digits.length; i++) {
        total += digits[i];
    }
    System.out.println(total);
    while(total >= 0) {
        if(total >= oNum) { 
        newBase.add(total - oNum);
        total -= oNum;
        System.out.println(total);
        }
        else {
            newBase.add(total);
        }
    }
    int[] ans = newBase.stream().mapToInt(i->i).toArray();
    System.out.println(Arrays.toString(ans));
}

This method is meant to convert a number in base 10 to a number in baseX. Its unfinished, and i keep getting multiple errors:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    at java.util.Arrays.copyOf(Unknown Source)
    at java.util.Arrays.copyOf(Unknown Source)
    at java.util.ArrayList.grow(Unknown Source)
    at java.util.ArrayList.ensureExplicitCapacity(Unknown Source)
    at java.util.ArrayList.ensureCapacityInternal(Unknown Source)
    at java.util.ArrayList.add(Unknown Source)
    at BaseConverter.toX(BaseConverter.java:34)

line 33-35 is:

else {
    newBase.add();
}

I THINK that the problem is coming from the stream, but I am very inexperienced with stream and arraylists.

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
  • 1
    I spot an infinite loop problem with `oNum=0`. Further, you can so some `mapToInt` trick to reverse the digits without needing a loop: https://stackoverflow.com/questions/24010109/java-8-stream-reverse-order – Mark Jeronimus Sep 29 '17 at 15:10
  • Think about what happens if total >=0 but less than oNum ;) – Steve B. Sep 29 '17 at 15:12

1 Answers1

0
while(total >= 0) {
    if(total >= oNum) { 
        newBase.add(total - oNum);
        total -= oNum;
        System.out.println(total);
    }
    else {
        newBase.add(total);
    }
}

If you hit the else branch it'll keep adding items to newBase without changing total, leading to an infinite loop.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • This is incorrect for most of the cases, since total gets subtracted by `oNum` if `total >= oNum` condition is met. – CrazySabbath Sep 29 '17 at 15:15
  • 1
    @CrazySabbath It's not guaranteed to give the error in all cases, but so what? This is clearly what is happening. – D M Sep 29 '17 at 15:36