-4
String haiku1 = "As the wind does blow\nAcross the trees, I see the\nBuds blooming in May."; 
String haiku2 = "I walk across sand\nAnd find myself blistering\nIn the hot, hot heat."; 
String haiku3 = "Falling to the ground,\nI watch a leaf settle down\nIn a bed of brown.";  
String haiku4 = "It’s cold and I wait\nFor someone to shelter me\nAnd take me from here.";  

我需要从上面列出的四个中打印一个随机字符串。我怎么能这样做?我知道我必须使用随机。谢谢你的帮助

4

7 回答 7

4

最好把你的字符串放在一个数组中。

String haiku[] = new String[4];
haiku[0] = "/*your string*/";
haiku[1] = "/*your string*/";
haiku[2] = "/*your string*/";
haiku[3] = "/*your string*/";

然后从 0-3 生成随机数以访问数组的索引。

Random randomizer = new Random();         //import java.util.Random;
int index = randomizer.nextInt(4);
System.out.println("Generated random string: " + haiku[index]);
于 2013-01-10T07:33:42.903 回答
2

像这样 -

    ...
    int nextInt = new Random().nextInt(4);
    switch (nextInt) {
    case 1:
        System.out.println(haiku1);
        break;
    case 2:
        System.out.println(haiku2);
        break;
    case 3:
        System.out.println(haiku3);
        break;
    case 4:
        System.out.println(haiku4);
        break;

    }
于 2013-01-10T07:35:35.257 回答
0

创建上述字符串的数组并使用java.util.Random类为数组索引生成随机数。

于 2013-01-10T07:32:17.407 回答
0

你应该把这个字符串放在一个数组中。

如需进一步参考,请查看以下链接。 从 ArrayList 中检索随机项

于 2013-01-10T07:36:49.867 回答
0

生成一个随机数,然后访问存储在数组中特定位置的值:

  Random r = new Random();
  int index = r.nextInt(4);
于 2013-01-10T07:37:27.000 回答
0

我会这样做:

String[] myArray = {haiku1,haiku2,haiku3,haiku4};
Random rand = new Random();
int randomnum = rand.nextint(4);
System.out.println(myArray[randomnum]);
于 2013-01-10T07:37:40.907 回答
0
   String haiku1 = ("As the wind does blow\nAcross the trees, I see the\nBuds blooming in May.");
    String haiku2 = ("I walk across sand\nAnd find myself blistering\nIn the hot, hot heat.");
    String haiku3 = ("Falling to the ground,\nI watch a leaf settle down\nIn a bed of brown.");
    String haiku4 = ("It’s cold and I wait\nFor someone to shelter me\nAnd take me from here.");

    String[] array={haiku1,haiku2,haiku3,haiku4};

    Random rndm=new Random();

    System.out.println( "Generated Random String: "+array[rndm.nextInt((array.length-1) - 0 + 1) + 0]);
于 2013-01-10T07:37:52.643 回答