Using random with strings in java ?

2019-02-16 06:06发布

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?

标签: java random
6条回答
迷人小祖宗
2楼-- · 2019-02-16 06:45
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)); 
    }
}
查看更多
劳资没心,怎么记你
3楼-- · 2019-02-16 06:48
String[] s = {"your", "array", "of", "strings"};

Random ran = new Random();
String s_ran = s[ran.nextInt(s.length)];
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-02-16 06:50

Use that integer value that you select randomly as the index for your array of strings.

查看更多
手持菜刀,她持情操
5楼-- · 2019-02-16 06:58
  1. Put your strings in an array.
  2. 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).
  3. Get the string by indexing into the array with the number you just got.
查看更多
Melony?
6楼-- · 2019-02-16 07:04

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);
查看更多
混吃等死
7楼-- · 2019-02-16 07:06
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.

查看更多
登录 后发表回答