2014-09-30 38 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(); 

我認爲這解決了您的問題。