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.";
我需要在上面列出的四个中打印一个随机字符串。我怎么能这样做?我知道我必须随机使用。谢谢你的帮助
答案 0 :(得分: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]);
答案 1 :(得分: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;
}
答案 2 :(得分:0)
创建上述字符串的数组,并使用java.util.Random
类为数组索引生成随机数。
答案 3 :(得分:0)
您应该将此字符串放在数组中。
进一步参考请在下面链接chekc。 Retrieving a random item from ArrayList
答案 4 :(得分:0)
生成一个随机数,然后访问存储在数组中特定位置的值:
Random r = new Random();
int index = r.nextInt(4);
答案 5 :(得分:0)
我会这样做:
String[] myArray = {haiku1,haiku2,haiku3,haiku4};
Random rand = new Random();
int randomnum = rand.nextint(4);
System.out.println(myArray[randomnum]);
答案 6 :(得分: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]);