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?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
import java.util.Random;
public class RandomSelect {
public static void main (String [] args) {
String [] arr = {"A", "B", "C", "D"};
Random random = new Random();
// randomly selects an index from the arr
int select = random.nextInt(arr.length);
// prints out the value at the randomly selected index
System.out.println("Random String selected: " + arr[select]);
}
}
Using charAt:
import java.util.Random;
public class RandomSelect {
public static void main (String [] args) {
String text = "Hello World";
Random random = new Random();
// randomly selects an index from the arr
int select = random.nextInt(text.length());
// prints out the value at the randomly selected index
System.out.println("Random char selected: " + text.charAt(select));
}
}
回答2:
- Put your strings in an array.
- Then get a random integer from the
Random
class that's within the bounds of the length of your array (look at the modulo%
operator to figure out how to do this; alternatively, constrain the call to random.nextInt() by passing an uppper bound). - Get the string by indexing into the array with the number you just got.
回答3:
Use that integer value that you select randomly as the index for your array of strings.
回答4:
String[] s = {"your", "array", "of", "strings"};
Random ran = new Random();
String s_ran = s[ran.nextInt(s.length)];
回答5:
shuffle(List list) Randomly permutes the specified list using a default source of randomness.
// Create a list
List list = new ArrayList();
// Add elements to list
..
// Shuffle the elements in the list
Collections.shuffle(list);
list.get(0);
回答6:
Random r = new Random();
System.out.println(list.get(r.nextInt(list.size())));
this will generate a random number between 0 [inclusive] and list.size() [non-inclusive]. Then, just get that element at that index out of the list.