1

I may be missing something obvious here, however using Labels in libgdx which take a string for the text to display I'm having trouble pointing a a random String.

String Movie1 ="The Shawshank Redemption (1994)";
String Movie2="The Godfather (1972)";
String Movie3="The Godfather: Part II (1974)";
String Movie4="The Dark Knight (2008)";
String Movie5="Pulp Fiction (1994)";

randomNumber = random.nextInt(5) + 1;

MovieName= new Label(String,style)

What would I put in for string to point to correspond the randomNumber to the appropriate movie. I can't put in "Movie" + randomNumber because it would just say "Movie5" not the string

3 Answers 3

4

Are you trying to do something like: String s = Movie + randomNumber to get a variable name Movie1, Movie2, etc.? This is not possible unless the variables are all attributes of a particular class. Regardless, you should not attempt to do this. Instead, you should use an array or a List<String> to hold the variables. You could do something like this:

String[] movies = {"The Shawshank Redemption (1994)",
    "The Godfather (1972)",
    "The Godfather: Part II (1974)",
    "The Dark Knight (2008)",
    "Pulp Fiction (1994)"}

int randomNumber = random.nextInt(movies.length);

String myMovie = movies[randomNumber];
Sign up to request clarification or add additional context in comments.

5 Comments

actually it's possible, just not wise :-)
@HovercraftFullOfEels if they're class attributes via reflection?
@Leo In the original question, they were not class attributes. I'm editing my answer to reflect this (no pun intented).
@Leo: I respectfully retract.
@HovercraftFullOfEels no, I am who respect you and your long contribution to this community :-)
3

First you should put your Strings into an array of String or a collection such as an ArrayList<String>, and only then can you select a random one via a random index number.

e.g.,

Random random = new Random();
String[] movies = {"The Shawshank Redemption (1994)",
   "The Godfather (1972)",
   "The Godfather: Part II (1974)",
   "The Dark Knight (2008)",
   "Pulp Fiction (1994)"};


// later somewhere else in a method or constructor...
int randomNumber = random.nextInt(movies.length);
String randomMovieTitle = movies[randomNumber];

Comments

0

You could use a switch statement for example:

var result;
randomNumber = random.nextInt(5) + 1;

switch(randomNumber) {
    case 1:
        result = Movie1;
        break;
    case 2:
        result = Movie2;
        break;
    case 3:
        result = Movie3;
        break;
} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.