Java指向随机变量

时间:2014-08-26 00:24:38

标签: java string random label

我可能会遗漏一些明显的东西,但是在libgdx中使用标签,它会显示一个字符串以显示我在指向随机字符串时遇到问题。

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)

我将把字符串指向什么以指向randomNumber与相应的电影。我无法投入电影" + randomNumber,因为它只会说" Movie5"不是字符串

3 个答案:

答案 0 :(得分:4)

您是否尝试执行以下操作:String s = Movie + randomNumber以获取变量名称Movie1Movie2等?除非变量是特定类的所有属性,否则这是不可能的。无论如何,你不应该试图这样做。相反,您应该使用数组或List<String>来保存变量。你可以这样做:

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];

答案 1 :(得分:3)

首先,你应该将你的字符串放入一个字符串数组或一个集合,例如ArrayList<String>,然后才可以通过随机索引号选择一个随机字符串。

如,

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];

答案 2 :(得分:0)

您可以使用switch语句,例如:

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

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