2012-06-06 75 views
-3

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

+4

你需要发布你试过的东西 –

回答

2

使用您随机选择的整数值作为您的字符串数组的索引。

5
  1. 将你的字符串放在一个数组中。
  2. 然后从Random类中得到一个随机整数,它位于数组长度的范围内(查看模%运算符以了解如何执行此操作;或者,通过传递来限制对random.nextInt()的调用一个上限)。
  3. 通过索引到刚刚获得数字的数组中获取字符串。
7
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)); 
    } 
} 
+0

另外,我怎样才能做到这一点使用indexOf()? –

+0

我更新了答案,从字符串中随机选择一个字符。你想用indexOf()来做什么? indexOf()用于定位字符串中的子字符串。 –

0

洗牌(名单列表) 随机的置换使用随机的默认源指定列表。

// Create a list 
List list = new ArrayList(); 

// Add elements to list 
.. 

// Shuffle the elements in the list 
Collections.shuffle(list); 
list.get(0); 
+0

技术上虽然解决了这个问题,但这可能是最低效率的方式。看到我的回答如下 – Matt

+0

你是对的,但对于这样的事情,我肯定是一个家庭作业,我只是想给一个替代方法。 –

0
Random r = new Random(); 
System.out.println(list.get(r.nextInt(list.size()))); 

这将产生0 [包容]和则为list.size之间的随机数()[非包含]。 然后,只需将该索引从列表中取出即可。

1
String[] s = {"your", "array", "of", "strings"}; 

Random ran = new Random(); 
String s_ran = s[ran.nextInt(s.length)];