2013-11-25 33 views
0

這是我的課程,用於查找句子中空格的數量,元音的數量和輔音的數量。它工作正常,但我需要它忽略的情況。我該怎麼做呢?我對「忽略案例」代碼很熟悉,但我不知道把它放在這個特定的程序中。字符串中的LowerCase和upperCase

  public class Counting{ 
      private String sentence; 
      private int spaces; 
      private int vowels; 
      private int consonants; 


      public Counting(){ 
       sentence = new String(); 
       spaces = 0; 
       vowels = 0; 
       consonants = 0; 

      } 

      public void setSentence(String sentence){ 
       this.sentence = sentence; 
      } 

      public void compute(){ 
       for(int i =0; i < sentence.length();i++){ 
        char letter = sentence.charAt(i); 
         if(sentence.charAt(i)==' '){ 
          spaces++; 

          } 
         else if((letter=='a')||(letter=='e') 
           ||(letter=='i')||(letter=='o')||(letter=='u')) 
            vowels++; 

         else{ 
     consonants++; 
     } 
     } 
          } 

      public int getSpaces(){ 
       return spaces; 
      } 

      public int getVowels(){ 
    return vowels; 
     } 
public int getConsonants(){ 
    return consonants; 
      } 

}

回答

3

一種常見的方式做,這是簡單地將原始字符串轉換爲小寫。

2

轉換傳遞給你的類爲小寫的字符串:

 public Counting(){ 
      setSentence(""); 
      spaces = 0; 
      vowels = 0; 
      consonants = 0; 

     } 

     public void setSentence(String sentence){ 
      this.sentence = sentence.toLowerCase(); 
     } 
+0

這不是很好的做法,因爲您可能在代碼中稍後需要原始語句。但這是一個很好的開始構思:讓'this.sentence = sentence.toLowerCase(); this.lowerCaseSentence = sentence.toLowerCase()'好像好多了。 – stackular

+0

我把它放在這個方法中。設置方法()。而且它是有效的。謝謝 – user109649

2

使用

letter.equalsIgnoreCase("a") 

用於檢查letterAa

+0

請注意,比較是針對字符串「a」,而不是字符「a」。 –

1

把它放在你compute()方法。這不是非常有效,但這是最簡單的事情。

public void compute() { 
    String lowerCaseSentence = sentence.toLowerCase(); 
    //... 
} 

而且隨着lowerCaseSentence在代碼的其餘部分在compute()

+1

stackular謝謝你,沒有probs – user109649

1

更換sentence是的,最好的辦法是將整個輸入句子轉換爲大寫或小寫和開展需要的操作

2

它可能會更容易只維護一組的所有元音,輔音,包括上,下外殼 - 你的代碼是將包括數字和標點符號作爲輔音

if (consonents.contains(c)) consonents++; 
else if (vowels.contains(c)) vowels++; 
else if (spaces.contains(c)) spaces++ 

或者你可以保持地圖一個char和財產(枚舉從0開始,並加上1,幷包括雜項作爲包羅萬象的),然後自顧自地產權計數組成的數組:

counts[property.get(c)]++; 
1

嘗試它:

sentence.toLowerCase(); 
相關問題