Hi! I am beginner in Java Programming and I am currently working with a program that randomly populate 14 buttons with a letter based on a given set of words and if the size of the word is less than the size of the button, it'll just populate it with random alphabets.
So here's the scenario:
i have an array of 14 buttons arranged like this:
[ 0] [ 1] [ 2] [ 3] [ 4] [ 5] [ 6]
[ 7] [ 8] [ 9] [10] [11] [12] [13]
i have this method setBtnLetter which sets a letter for each button as its label.
this method works fine as long as the word is less than 14 letters (1-13 letters),
but when i change a default value for String variable word with 14 letters,
my program freezes. is the program having an infinite loop?

Variables & Legends:
word - String variable declared globally
- has a value of "She Will Be Loved" (When i encountered the freeze)
counter - Int variable declared globally
- stored here is the size of the word
ltrCount - Int var declared globally
- used to count the entered letter and later compared to counter
val - an object of Random (Random val = new Random())
btnLtr - array of buttons (Buttons[] btnLtr = new Buttons[14])
alphabet - String variable
- contains "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

here's the code:

public void setBtnLetter(){
        String trimmedWord = word.replaceAll("\\s","").toUpperCase();
        counter = (int) trimmedWord.length();
        ltrCount = 0;
        while(ltrCount != counter){
            val = rand.nextInt(13);
            if(btnLtr[val].getText().toString().trim().isEmpty()){
                btnLtr[val].setText(""+trimmedWord.charAt(ltrCount));
                ltrCount++;
            }   
        }

        for(int x = 0; x < btnLtr.length; x++){
            if(btnLtr[x].getText().toString().trim().isEmpty()){
                btnLtr[x].setText(""+alphabet.charAt(rand.nextInt(25)));
            }   
        }
    }

I can't figure out what's wrong with this code, it took me already several days but still no luck..

Thanks in advance..

Recommended Answers

All 4 Replies

Your random numbers are in the range 0-12 so your first loop will never be able to process 14 letters, but it keeps on trying...

Ps. Your second loop will never select Z, for the same reason. It seems you have mistaken the contract for nextInt - review the API doc ;)

The method nextInt(n) call returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and n (exclusive).

so this means that if i used nextInt(13), the range is only from 0-12?

Thanks JamesCherrill!

That's right.
Similarly, rand.nextInt(25) will give you random ints in the range 0-24 inclusive.
Think of the parameter as defining how many different values it will return.

Thanks! It worked great!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.