Skip to content
Advertisement

How to expand a number to match another in Java

I’m given a number for example 319 and i need to write code that will break out a number to 3192310, for example. I’ll try to explain how it needs to be done and what i’ve tried.

Explanation: (given two inputs: 319 and 3192310) So the program starts by appending 0 to 9 at the end of 319, and compares that fourth digit to the fourth digit in 3192310. In this case, that digit would be “2”. At the line 3192, the program appends 0 to 9 at the end of 3192, and compares the fifth digit to the fifth digit in 3192310. In this case, that digit would be “3”. the program continues until it reaches the end and a “bingo” string is appended to 3192310.

Here’s an example of what the output should be:

JavaScript

My attempt: So I had started by first taking the last 4 characters of the input from a JTextField and placing it in an array. Then I created a for loop with an if and else statement comparing the index of the for loop to the value of the array at a given index. If the index of the for loop matched the value of the array, called the funtion again (recursive function). See my code below:

JavaScript

But this is my output:

JavaScript

I’ve gone through my code and I get how I got the output, I’m just not sure how to change it. I feel lke I need some sort of nested for loop but I’m not sure. Can anyone help me out. Thanks

Advertisement

Answer

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:

JavaScript

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

JavaScript

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:

JavaScript

Output using 319 and 3192310 follows:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement