生成Java中随机单词? [英] Generating random words in Java?

查看:383
本文介绍了生成Java中随机单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个程序,可以进行排序的话,并确定任何字谜。我要生成随机字符串数组,这样我可以测试我的方法的运行时间。

I wrote up a program that can sort words and determine any anagrams. I want to generate an array of random strings so that I can test my method's runtime.

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

(方法存根)

我只想长度1-10小写的话。我读了一些有关生成随机数,然后转换为char或什么的,但我没有完全理解。如果有人能告诉我如何生成随机的话,那么我应该能够轻松地只使用一个for循环插入文字到数组。谢谢!

I just want lowercase words of length 1-10. I read something about generating random numbers, then casting to char or something, but I didn't totally understand. If someone can show me how to generate random words, then I should easily be able to just use a for loop to insert the words into the array. Thanks!

推荐答案

您是否需要实际英语单词,或者只包含字母A-Z只是随机字符串?

Do you need actual English words, or just random strings that only contain letters a-z?

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

If you need actual English words, the only way to do it is to use a dictionary, and select words from it at random.

如果您不需要英语单词,那么这样的事情就可以了:

If you don't need English words, then something like this will do:

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;
}

这篇关于生成Java中随机单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆