创建具有一定数量的元音和辅音的字符数组(Java)

问题描述 投票:2回答:3

我正在尝试创建一个输出十个小写字母字符的程序 - 五个元音和五个辅音。为了做到这一点,我开始创建一个char数组,其范围介于'a''z'之间,名为letters[],大小为10.一旦数组填满,我将使用包含数组中所有内容的格式字符串打印输出。

我的问题是,如何使程序输出正好五种类型(并保持字符的顺序完全随机)?我考虑过使用switch语句,每个语句都有辅音和元音,但到目前为止我的想法似乎过于复杂和不优雅。

代码到目前为止:

char letters[] = new char[10];
for(int i = 0; i < letters.length; i++){ //Open for

letters[i] = (char)(97 + Math.random() * 26);
char idx = letters[i];

System.out.printf("%s",idx);

} //End for
java arrays random character
3个回答
0
投票

如果你不介意更多与字符串相关的解决方案,这里就是一个。我假设您不希望在输出字符串中重复任何辅音或元音,因此该算法在使用后会删除字母以供考虑。它还提供了一些通用的字母选择程序,它并不仅限于元音和辅音。

import java.lang.StringBuilder;

public class Shuffler {
    public static String CONSONANTS = "bcdfghjklmnpqrstvwxyz";
    public static String VOWELS = "aeiou";

    /*
     * Returns a new string that is a combination of the current string and 'count'
     * characters from the source string (using any character in the source string
     * no more than one time).
     */
    public static String shuffleIntoString(String current, String source, int count) {
        if (current == null || source == null || count < 0 || count > source.length()) {
            System.out.println("Error in parameters to shuffleIntoString");
            return null;
        }

        StringBuilder retval = new StringBuilder(current);        // build up by inserting at random locations
        StringBuilder depletedSource = new StringBuilder(source); // remove characters as they are used

        for (int i = 0; i < count; i++) {
            int pick = (int) (Math.random() * depletedSource.length());
            int whereToInsert = (int) (Math.random() * retval.length());
            retval = retval.insert(whereToInsert, depletedSource.charAt(pick));
            depletedSource.deleteCharAt(pick);
        }

        return retval.toString();
    }

    public static void main(String[] args) {
        Shuffler shuf = new Shuffler();

        for (int i = 0; i < 10; i++) {
            String result = shuf.shuffleIntoString("", shuf.CONSONANTS, 5);
            result = shuf.shuffleIntoString(result, shuf.VOWELS, 5);
            System.out.println(result);
        }
    }
}

输出看起来像这样:

kqoibauzed
uhcawoerib
afdzoemius
yuagocibej
eiuhaokcyq
ouveiawrxn
uyaiveomxn
ruxeoalhij
uraliwfeoc
afoutiesmr

0
投票

如果您满足于使用ArrayLists,这将达到您的要求。要生成随机字符,您可以在相应的字符串字符串的索引中生成一个数字,并将该值添加到ArrayList。 Collections是一个有用的类,您可以使用它来洗牌。

List<Character> list = new ArrayList<>();

String consonants = "bcdfghjklmnpqrstvwxyz";
String vowels = "aeiou";

Random r = new Random();

for (int i = 0; i < 5; i++) {
    list.add(consonants.charAt(r.nextInt(consonants.length()))); // Add consonant
    list.add(vowels.charAt(r.nextInt(vowels.length()))); // Add vowel
}
Collections.shuffle(list);

for (Character c : list) {
    System.out.println(c);
}

0
投票

我没有看到任何关于重复的规则但是如果你想要你可以在选择后从数组中删除latters。

    List<Character> vowels = Arrays.asList('a', 'e', 'i', 'o', 'u');

    List<Character> consonants = new ArrayList<>();

    for (char latter = 'a'; latter <= 'z'; latter++) {
        if(!vowels.contains(latter)) {
            consonants.add(latter);
        }
    }

    final Random random = new Random();

    int vowelsRemain = 5;
    int consonantsRemain = 5;

    List<Character> result = new ArrayList<>();

    while (vowelsRemain > 0 && consonantsRemain > 0) {
        final boolean generateVowel = random.nextBoolean();

        final char randomLatter;

        if(generateVowel) {
            randomLatter = vowels.get(random.nextInt(vowels.size()));
            vowelsRemain--;
        } else {
            randomLatter = consonants.get(random.nextInt(consonants.size()));
            consonantsRemain--;
        }

        result.add(randomLatter);
    }

    while (vowelsRemain > 0) {
        final Character randomVowel = vowels.get(random.nextInt(vowels.size()));
        result.add(randomVowel);

        vowelsRemain--;
    }

    while (consonantsRemain > 0) {
        final Character randomConsonant = consonants.get(random.nextInt(consonants.size()));
        result.add(randomConsonant);

        consonantsRemain--;
    }

    System.out.println(result);
© www.soinside.com 2019 - 2024. All rights reserved.