在Java中生成随机单词?

我写了一个程序,可以对单词进行排序并确定任何字谜。 我想生成一个随机字符串数组,以便我可以测试我的方法的运行时。

public static String[] generateRandomWords(int numberOfWords){ String[] randomStrings = new String[numberOfWords]; Random random = Random(); return null; } 

(方法存根)

我只想要长度为1-10的小写单词。 我读了一些关于生成随机数,然后转换为char或其他东西的东西,但我并不完全理解。 如果有人可以告诉我如何生成随机单词,那么我应该能够轻松地使用for循环将单词插入到数组中。 谢谢!

你需要实际的英语单词,还是只需要包含字母az的随机字符串?

如果您需要实际的英语单词,唯一的方法是使用字典,并随机选择单词。

如果你不需要英语单词,那么这样的话会:

 public static String[] generateRandomWords(int numberOfWords) { String[] randomStrings = new String[numberOfWords]; Random random = new Random(); for(int i = 0; i < numberOfWords; i++) { char[] word = new char[random.nextInt(8)+3]; // words of length 3 through 10. (1 and 2 letter words are boring.) for(int j = 0; j < word.length; j++) { word[j] = (char)('a' + random.nextInt(26)); } randomStrings[i] = new String(word); } return randomStrings; } 

来自commons-lang的RandomStringUtils

如果要生成给定长度的随机单词,您需要一个算法来确定给定的字符串是一个单词(硬),还是需要访问给定语言中所有单词的单词列表(简单)。 如果它有帮助, 这里是Scrabble字典中每个单词的列表 。

获得语言中所有单词的列表后,可以将这些单词加载到ArrayList或其他线性结构中。 然后,您可以在该列表中生成随机索引以获取随机单词。

如果你想要随机单词而不使用字典……

  1. 列出您想要的所有字母
  2. 生成随机索引以从列表中选取一个字母
  3. 重复,直到您拥有所需的字长

对要生成的单词数重复这些步骤。

您可以为要生成的每个单词调用此方法。 请注意,产生字谜的概率应该相对较低。

 String generateRandomWord(int wordLength) { Random r = new Random(); // Intialize a Random Number Generator with SysTime as the seed StringBuilder sb = new StringBuilder(wordLength); for(int i = 0; i < wordLength; i++) { // For each letter in the word char tmp = 'a' + r.nextInt('z' - 'a'); // Generate a letter between a and z sb.append(tmp); // Add it to the String } return sb.toString(); } 

为什么生成随机单词? 什么时候可以使用一些词典 。