2014-09-30 55 views
3

这是我到目前为止有:在Java中,如何创建一个简单的程序来打印短语中辅音和元音的数量?

System.out.println("CONSONANT AND VOWEL COUNTER: Please type a phrase: "); 
    String lastPhrase = keyboard.nextLine(); 

    int countCon = 0; 
    int countVow = 0; 

    if (lastPhrase.contains("bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ")) { 
     countVow++; 
    } 
    if (lastPhrase.contains("abcdefghijklmnopqrstuvwxyzABCDEFGHJKLIMNOPQRSTUVWXYZ")) { 
     countCon++; 
    } 
    System.out.println("There are " + countVow + " vowels and " + countCon + " consonants."); 

它配备了0这两个值。有什么问题?

+0

你在问'lastPhrase'是否包含这些长字符串。可以? – 2014-09-30 02:56:38

+1

您将需要'loop'和'charAt()'。 – 2014-09-30 02:57:52

回答

1

根据Java文档

字符串包含(CharSequence中) 返回true当且仅当此字符串包含char值的指定序列。

计算元音数量最简单的方法是循环并检查字符串对象的每个字符。

String s = "Whatever you want it to be.".toLowercase(); 
int vowelCount = 0; 
for (int i = 0, i < s.length(); ++i) { 
    switch(s.charAt(i)) { 
     case 'a': 
      vowelCount++; 
      break; 
     case 'e': 
      vowelCount++; 
      break; 
     case 'i': 
      vowelCount++; 
      break; 
     case 'o': 
      vowelCount++; 
      break; 
     case 'u': 
      vowelCount++; 
      break; 
     default: 
      // do nothing 
    } 
} 
+0

使用String.matches()和元音和辅音的正则表达式要好得多。没有太多更复杂的。 – 2014-09-30 03:03:09

+0

同意。有多种方法可以解决这个问题。 String.matches()是一种更优雅的方式,但Zander必须首先使用正则表达式。 – 2014-09-30 03:06:38

4

contains搜索整个字符串,而不是单个字母。

最简单的方法来做到这一点,从我脑海的顶部假设没有神奇的String方法我失踪,将手动检查每个字符。

您应该使用toUpperCase将整个字符串转换为大写,然后检查该字符是否为元音AEIOU。

if(string.charAt(i) == 'A' || ... /* and so on */) { 
    countVow++; 
} 
else { 
    countCons++; 
} 

如果是,则将元音加1。否则,加1到辅音。它不是元音就是辅音,所以如果你只检查这五个字符,你就知道它是什么。

由于这可能是一个家庭作业问题,我已经为您提供了朝正确方向迈出的一步。如果您需要帮助,您应该努力寻找解决方案并回来。

+0

如果字符串有数字或标点符号怎么办?然后它不会工作。 – 2014-09-30 03:21:10

+0

@RenéG那么你可以在'else'中使用'isLetter()'作为'else if'。 – Compass 2014-09-30 12:57:15

+0

我试过这个,但它说第一个类型布尔第二类型字符。我该如何解决? – 2014-10-01 23:49:35

0

我会做这样的:

//convert string to lowercase 
//for loop looping over the string  
if(string.charAt(i).matches([aeiou]) { 
     countVow++; 
} 
else if(isLetter(string.charAt(I))){ 
     countCons++; 
} //end for loop 

String.matches()regular expressions

1

类似的东西

String vowels = "aeuyio"; 
String consonants = "bcdfgh..." 

String phrase = "amsdasmdnsn"; 

int vowelsCount = 0, consonantsCount = 0; 
for (char ch : phrase.toCharArray()) { 
    if (vowels.contains(String.valueOf(ch))) { 
     ++vowelsCount; 
    } 

    if (consonants.contains(String.valueOf(ch))) { 
     ++consonantsCount; 
    } 
} 
0

String.contains仅适用于字符串和正则表达式。计算所有辅音我能想到的最快方法是:

String onlyConsonants = lastPhrase.replaceAll("[\\saeiouAEIOU0-9]", ""); 
countCon = onlyConsonants.length(); 
String onlyVowels = lastPhrase.replaceAll("[^\\saeiouAEIOU0-9]", ""); 
countVow = onlyVowels.length(); 

我认为这解决了您的问题。