2017-07-20 35 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:如何计算字符串中char的出现次数?](https://stackoverflow.com/questions/275944/java-how-do-i-count-of-a-char-in-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]); 
    } 

}