2017-07-20 1 views
1

次のようなプロジェクトを完了する必要があります。 単語の文字列を入力するようにユーザーに指示し、アルファベットの各文字が表示される回数をカウントして表示するプログラムを作成します。文字列 は、大文字と小文字を区別する必要はありません。それは次のようになりますので、私はそれを編集したJava文字列プロジェクトのエラー

Letter A count = xx 
Letter B count = xx 

.... 
Letter Z count = xx 

: は次のように出力をフォーマットする必要があります。今の唯一の問題は、大文字が文字カウント中に無視されていることです。問題の内容がわかりません。

public class Assignment9 { 

    public static void main(String[] sa) { 

     int letters [] = new int[ 26 ]; 
     String s; 
     char y; 

     for (int x = 0; x < letters.length; x++) 
     { 
      letters[x] = 0; 
     } 

     s = Input.getString("Type a phrase with characters only, please."); 
     s.toLowerCase(); 

     for (int x = 0; x < s.length(); x++) 
     { 
      y = s.charAt(x); 
      if (y >= 'a' && y <= 'z') 
      { 
       letters[ y - 'a' ]++; 
      } 

     } 

     for (y = 'a'; y <= 'z'; y++) 
     { 
      System.out.println("Letter " + y + " = " + letters[ y - 'a'] + " "); 
     } 

    } 

} 
+2

ヒント:現在、カウントループ*内のすべての文字*の数が表示されています。 –

+0

カウント部分が終了した後にカウントを出力し、あなたが計算している間に値を出力する – ja08prat

+0

[Java:文字列中の文字の出現回数をカウントするにはどうすればいいですか?](https://stackoverflow.com/question/275944/java-how-do-i-count-of-a-string-of-a-string-of-a-string) – hwdbc

答えて

0

次のループを使用して、入力文字列を反復処理しているループの外でなければなりませんので、あなたは、最初の文字をカウントし、その結果を表示する必要があります。

for (y = 'a'; y <= 'z'; y++) 
{ 
    System.out.println("Letter " + y + " = " + letters[ y - 'a'] + " "); 
} 
0

私はあなたのためのソリューションを持っています:

public static void main(String[] args) { 

    //Init your String 
    String str = "Your string here !"; 
    str = str.toLowerCase(); 

    //Create a table to store number of letters 
    int letters [] = new int[ 26 ]; 

    //For each char in your string 
    for(int i = 0; i < str.length(); i++){ 
     //Transphorm letter to is corect tab index 
     int charCode = (int)str.charAt(i)-97; 

     //Check if the char is a lettre 
     if(charCode >= 0 && charCode < 26){ 
      //Count the letter 
      letters[charCode]++; 
     } 
    } 

    //Display the result 
    for(int i = 0; i < 26; i ++){ 
     char letter = (char)(i+65); 
     System.out.println("Letter " + letter + " count = " + letters[i]); 
    } 

}