-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.";  

I need to print a random string out of the four listed above. How could I do this? I know I must use random. Thanks for any help

rai.skumar
  • 10,309
  • 6
  • 39
  • 55
user1755022
  • 77
  • 3
  • 8

7 Answers7

4

It's better to put your strings in an array.

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

Then generate random number from 0-3 to access the index of your array.

Random randomizer = new Random();         //import java.util.Random;
int index = randomizer.nextInt(4);
System.out.println("Generated random string: " + haiku[index]);
Jj Tuibeo
  • 773
  • 4
  • 18
2

Like this -

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

    }
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
0

Create an array of your above Strings and use java.util.Random class to generate random number for array index.

Nandkumar Tekale
  • 16,024
  • 8
  • 58
  • 85
0

You should put this strings in an array.

for further reference please chekc below link. Retrieving a random item from ArrayList

Community
  • 1
  • 1
0

Generate a random number and then access value stored at particular position in array:

  Random r = new Random();
  int index = r.nextInt(4);
rai.skumar
  • 10,309
  • 6
  • 39
  • 55
0

I would do it this way:

String[] myArray = {haiku1,haiku2,haiku3,haiku4};
Random rand = new Random();
int randomnum = rand.nextint(4);
System.out.println(myArray[randomnum]);
Abs
  • 1,726
  • 2
  • 17
  • 28
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]);
amicngh
  • 7,831
  • 3
  • 35
  • 54