我试图随机选择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]);
}
}
Run Code Online (Sandbox Code Playgroud)
使用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));
}
}
Run Code Online (Sandbox Code Playgroud)
Random类中获取一个随机整数,该类在数组长度的范围内(查看模%运算符以了解如何执行此操作;或者,通过传递一个uppper绑定来约束对random.nextInt()的调用).