在java中随机使用字符串?

Ber*_*mas -2 java random

我试图随机选择4个字符串中的字符串,并在控制台上显示此字符串.我该怎么做 ?例如,有一个问题,如果用户正确回答,那么控制台将显示我选择的一个字符串.我知道如何随机选择一个整数值,但我无法弄清楚如何随机选择一个字符串.请帮忙?

Lai*_*Chu 9

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)


Est*_*aya 5

  1. 把你的字符串放在一个数组中.
  2. 然后从Random类中获取一个随机整数,该类在数组长度的范围内(查看模%运算符以了解如何执行此操作;或者,通过传递一个uppper绑定来约束对random.nextInt()的调用).
  3. 通过使用您刚刚获得的数字索引到数组中来获取字符串.