I am trying to choose a string out of 4 strings randomly, and to show this string on the console. How can i do it ? For example, there is a question, if user answers it correctly, then the console will display one of the strings that i chose. I know how to choose an integer value randomly, but i could not figure out how to choose a string randomly. Please Help?

Recommended Answers

All 4 Replies

Put the strings into an array and use the randon int (0-3) as the index to retrieve one element of the array.

String[] stringNum = {"Good","Fine","Gorgeous","Pretty Good" }; 
    int stringSec = myRandom.nextInt(3); 
    for (String element:stringNum){
        System.out.println("Index is: " + element.indexOf(stringSec));
    }//end for

What is wrong with this code ? I don't know arrays well but can you please explain ?

Why do you think there is something wrong with the code you posted? If you are getting errors please post them. If the code doesn't do what you want it to, please explain.

Why do you think there is something wrong with the code you posted? If you are getting errors please post them. If the code doesn't do what you want it to, please explain.

OK. Guys i got it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.