在java中随机使用字符串?
我试图随机选择4个字符串中的字符串,并在控制台上显示此字符串。 我该怎么做 ? 例如,有一个问题,如果用户正确回答,那么控制台将显示我选择的一个字符串。 我知道如何随机选择一个整数值,但我无法弄清楚如何随机选择一个字符串。 请帮忙?
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]); } }
使用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)); } }
- 把你的字符串放在一个数组中。
- 然后从
Random
类中获取一个随机整数,该整数在数组长度的范围内(查看模数%
运算符以找出如何执行此操作;或者,通过传递一个uppper bound来约束对random.nextInt()的调用)。 - 通过使用您刚获得的数字索引到数组中来获取字符串。
使用随机选择的整数值作为字符串数组的索引。
String[] s = {"your", "array", "of", "strings"}; Random ran = new Random(); String s_ran = s[ran.nextInt(s.length)];
shuffle(列表列表)使用默认的随机源随机置换指定的列表。
// Create a list List list = new ArrayList(); // Add elements to list .. // Shuffle the elements in the list Collections.shuffle(list); list.get(0);
Random r = new Random(); System.out.println(list.get(r.nextInt(list.size())));
这将生成0 [包含]和list.size()[不包含]之间的随机数。 然后,只需从列表中的该索引处获取该元素。