For a trivial word game, I wrote the following code for the player to choose one of the two choices of words that in turn were read from a sentence.

My question lies in first in the click-listener of the buttons of the choice.

The main code, in Java:

private void initAnswerButtons() {

    //2. here
    if (questionNum == wordList.size()){
    String s = wordList.get(questionNum);
    String[] choices = s.split("/");
    int numOfChoices = choices.length;          
    for (int i=0; i<numOfChoices ; i++)            
        choiceButton[i] = new TextButton(choices[i], skin, "default");
        choiceButton[i].setPosition( 20 + i*120, app.camera.viewportHeight - 200);
        choiceButton[i].setSize(100, 50);
        choiceButton[i].addListener(new ClickListener() {

            //1. here
            public void clicked(InputEvent event, float x, float y) {
                if (questionNum == wordList.size()){


The wordList array which I have hard-coded for:

private void initWordlist() {
    wordList = new ArrayList<String>();
    wordList.add("ni sa udongo/si sa mawe");

The first question (see "1.here"): I am using a click-listener which is in the form of an anonymous class. As a result, I check whether I have run out of questions, i.e. if (questionNum == wordList.size()). If NOT so, it goes to the next question i.e. questionNum++ and then:


I callback the method itself, yes, recursively from inside the method. What would you do instead to avoid such a structure?

Second question: in order to avoid running out of questions and out of range of the wordList array, I put an if-check (see "2. here"). That doesn't look good either, but that is also a natural consequence of the present structure of the code.

So, what would you do instead?


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.