2013-01-10 42 views
-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打印1个随机字符串?

+0

您需要阅读[此](http://stackoverflow.com/questions/how-to-ask)和[this](http://meta.stackexchange.com/a/5235/164088)。 –

回答

0

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

+0

有没有办法做到这一点,而不使用数组? – user1755022

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

    } 
+0

重复的代码已被删除。 –

0

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

Random r = new Random(); 
    int index = r.nextInt(4); 
0

我会做这种方式:

String[] myArray = {haiku1,haiku2,haiku3,haiku4}; 
Random rand = new Random(); 
int randomnum = rand.nextint(4); 
System.out.println(myArray[randomnum]); 
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]);