#Get object type out of do-while

12 messages · Page 1 of 1 (latest)

lone storm
#

I have the following code:

                    // Select race and make sure it's not empty
                    do {
                        race = JOptionPane.showInputDialog(null, "Choose Race:", "Input", JOptionPane.INFORMATION_MESSAGE, null, racesNames, racesNames[0]);
                        if (!(race == null)) {
                            int raceIndex = ArrayUtils.indexOf(racesNames, race);
                            race = racesArray[raceIndex]; // Convert from name to full character JSONObject
                        }
                    }
                    while (race == null);

It's supposed to let the user select from a list of race names, and after being selected, it changes that race name object to be the full JSONObject of the race from another list with the same indexes.

If a race isn't selected, the dialog is reopened until a valid option is selected. However, I'm not sure how to manipulate the JSONObject past the do-while because Java doesn't know that it's going to be a JSONObject no matter what.

Is there any way around this? Thanks in advance!

waxen daggerBOT
#

This post has been reserved for your question.

Hey @lone storm! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

gilded crater
#

you could cast into another variable, but imo this could be refactored to not use the same variable for 2 different things.

#

(sidenote, !(race == null) could be rewritten as race != null)

lone storm
#
JSONObject raceObject = null;
do {
    race = JOptionPane.showInputDialog(null, "Choose Race:", "Input", JOptionPane.INFORMATION_MESSAGE, null, racesNames, racesNames[0]);
    if (race != null) {
        int raceIndex = ArrayUtils.indexOf(racesNames, race);
        raceObject = racesArray[raceIndex]; // Convert from name to full character JSONObject
    }
}
while (race == null);
``` instead ?
gilded crater
#

sure

#

seems like this could be extracted into a method to avoid race leaking into unrelated scopes

#

since you're checking the same condition twice here, you could also refactor this to just set raceObject after the loop as well

lone storm
#

gotcha, thanks !

waxen daggerBOT
# lone storm gotcha, thanks !

If you are finished with your post, please close it.
If you are not, please ignore this message.
Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.

gilded crater
#

make sure race is accessible only where it's supposed to be