只显示一种元音

时间:2015-04-22 03:51:33

标签: java

我只需要显示一种从字符串中检查过的元音类型 但它会不断显示重复的元音。

输入:我整天都在你身边,并且知道你。

输出:
元音:我是你 辅音:m n y d d w t h c r

这意味着它将显示句子中使用的元音。 同样适用于辅音

import java.util.Scanner;

public class aaaa {

public static void main(String[] args) {
    // TODO Auto-generated method stub

Scanner input = new Scanner (System.in);
System.out.println ("Enter a string:");
String s = input.nextLine();

char[] sChars = s.toCharArray();
char[] vowels = {'a','e','i','o','u','A','E','I','O','U'}; 
char[] consonant = {'b','c','d','f','g','h','k','j','l','m','n','p','q','r','s','t','x','v','w','y','z'};

for (int j = 0 ; j < sChars.length ; j++ ) {   
    for (int i = 0; i < vowels.length ; i++ ) {
        if ( sChars[j] == vowels[i]) {
            System.out.print(vowels[i]+ " ");
        }

    }
}
System.out.print("\n");
for(int m = 0 ; m < sChars.length ; m++){
    for(int n = 0; n < consonant.length ; n++){
        if ( sChars[m] == consonant[n]){
            System.out.print(consonant[n]+" ");
        }
    }
}

  }

}

2 个答案:

答案 0 :(得分:3)

试试这个:

System.out.println("Vowels: " + s.toLowerCase().replaceAll("[^aeiou]|(.)(?=.*\\1)", "") 
+ "\nConsonants: " + s.toLowerCase().replaceAll("[aeiou]|(.)(?=.*\\1)", ""));

通过使用正则表达式选择要删除的感兴趣字符,可以在一行中完成整个作业。

仅供参考,正则表达式[aeiou]|(.)(?=.*\1)表示&#34;任何元音,或任何不再出现的字符&#34;。交替的第一场比赛在那里停止,这就是为什么我不需要为右手边的辅音编码字符类 - 点只会匹配非元音。

类似的方法用于打印元音,除了它是否定的字符类。

答案 1 :(得分:0)

有更有效的方法可以做到这一点,但我会尝试尽可能少地改变你的解决方案。

跟踪已打印的字母,不要再次打印:

char[] vowels = {'A','E','I','O','U'}; 
char[] consonant = {'B','C','D','F','G','H','K','J','L','M','N','P','Q','R','S','T','X','V','W','Y','Z'};

// create a collection to store the letters already used
List<Character> lettersUsed = new ArrayList<Character>();
for (int j = 0 ; j < sChars.length ; j++ ) {   
    for (int i = 0; i < vowels.length ; i++ ) {
        if ( Character.toUpperCase(sChars[j]) == vowels[i]) {
            // if the collection of used letters does not contain this one
            if(!lettersUsed.contains(Character.toUpperCase(sChars[j]))) {
                System.out.print(sChars[j]+ " ");
                // add this letter to the collection of letters used
                lettersUsed.add(Character.toUpperCase(sChars[j]));
            }
            // now that you've found a match, break out of the inner loop
            break;
        }            
    }
}
System.out.print("\n");
for(int m = 0 ; m < sChars.length ; m++){
    for(int n = 0; n < consonant.length ; n++){
        if ( Character.toUpperCase(sChars[m]) == consonant[n]){
            // if the collection of used letters does not contain this one
            if(!lettersUsed.contains(Character.toUpperCase(sChars[m]))) {
                System.out.print(sChars[m]+" ");
                // add this letter to the collection of letters used
                lettersUsed.add(Character.toUpperCase(sChars[m]));
            }
            // now that you've found a match, break out of the inner loop
            break;
        }
    }
}