Click here to Skip to main content
15,881,281 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hey, i have this code

private void putTextOnButtons() {
        for (int i = 0; i < 4; i++) {
            int num = rand.nextInt(10) + 1;
            number[i] = num;
            buttons[i].setText(num + "");
            sortArray(number);
            for (int j = 0; j < 3; j++) {
                if (number[j] == number[j + 1])
                    putTextOnButtons();
            }
            sortArray(number);
        }
    }

But whenever i try to run it, it crashes and says
Process: com.example, PID: 12305<br />
  java.lang.StackOverflowError

and

> at com.example.gal.tapbynumber.EasyMainActivity.putTextOnButtons(EasyMainActivity.java:110)
Which takes to `putTextOnButtons();`
under the if.
I don't see any problem here, Any one can help me please?
Posted

I have solved it all i had needed to do is change from this
C#
private void putTextOnButtons() {
        for (int i = 0; i < 4; i++) {
            int num = rand.nextInt(10) + 1;
            number[i] = num;
            buttons[i].setText(num + "");
            sortArray(number);
            for (int j = 0; j < 3; j++) {
                if (number[j] == number[j + 1])
                    putTextOnButtons();
            }
            sortArray(number);
        }
    }

to this
C#
private void putTextOnButtons() {
        for (int i = 0; i < 4; i++) {
            int num = rand.nextInt(10) + 1;
            number[i] = num;
            buttons[i].setText(num + "");
            }
            sortArray(number);
            for (int j = 0; j < 3; j++) {
                if (number[j] == number[j + 1])
                    putTextOnButtons();
            }
            sortArray(number);
        
    }
 
Share this answer
 
In that case you should use a loop instead of recursivity. In the second loop set a variable that will indicate that there are some duplicates and add an outer loop that use that variable to loop the whole code of necessary.

By the way, it is not a good way to generate unique random numbers as if the sequence is long and generated numbers range is small, it can lead to a lot of retries or even almost infinite loop.

Given that you generated only small number, better to make a list of those and pick a number into that list untl you have all desired numbers.

Similar questions have been asked multilple times, so if you cannot figure it out, you can use Google.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900