how do you expand a number to match another in java?

I figured it out. Your code was originally throwing an IndexOutOfBoundsException because index was not being checked against breakoutArray.length - 1. After I fixed the exception, with if((index < breakoutArray.length - 1) && i == breakoutArray[index]), I was getting the following wrong output:

3190
3191
31920
31921
31922
319230
3192310 bingo
3192311
3192312
3192313
3192314
3192315
3192316
3192317
3192318
3192319
3192312 <-- this should be 319232
3192313 <-- this should be 319233
... and on and on

This took me a while to figure out, but it came down to altering number to number + i in this code:

if (i == breakoutArray[index]) {
    index += 1;
    number = number + i;
    recursivePrint(index, breakoutArray, number);
}

Using number = number + i sets number in that stack frame, as well as all subsequent recursive stack frames. This was remedied by passing number + i in the recursive call, via recursivePrint(index + 1, breakoutArray, number + i).

The complete, working, method code follows:

public void recursivePrint(int index, int[] breakoutArray, String number) {
    
    //number=319 is a String
    for (int i = 0; i <= 9; i++) {
    
        if ((index < breakoutArray.length - 1) && i == breakoutArray[index]) {
            recursivePrint(index + 1, breakoutArray, number + i);
        } else {
            
            if((index == breakoutArray.length - 1) && i == breakoutArray[index]) {
                rightOutputBText.append(number + i + " bingo\n");
            } else {
                rightOutputBText.append(number + i + "\n");
            }
            
        }
    
    }
} //end of recursivePrint method

Output using 319 and 3192310 follows:

3190
3191
31920
31921
31922
319230
3192310 bingo
3192311
3192312
3192313
3192314
3192315
3192316
3192317
3192318
3192319
319232
319233
319234
319235
319236
319237
319238
319239
31924
31925
31926
31927
31928
31929
3193
3194
3195
3196
3197
3198
3199

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top