-1

次のコードがあります。特定の文字の頻度を数えたいのですが、できません。誰でもヒントを提供できますか?

import java.io.*;
import java.lang.*;
public class Mywork {

    /**
    * @param args the command line arguments
    */
    public static void main(String[] args) {
        // TODO code application logic here
        try {
            String str;
            System.out.println("Enter a String:");
            DataInputStream d=new DataInputStream(System.in);
            str=d.readLine();
            int count=0;
            System.out.println("You Entered  "+str);
            char a[]=new char[str.length()];
            int i=0;
            System.out.println("enetr the characte of which frequency is to be count:");
            char c=(char)d.read();
            System.out.println("you entered "+c);
            while(str!=null){
                if(str.charAt(i)==c){
                    count++;
                } else {
                    i++;
                }
                i++;
            }   
            System.out.println("Frequency of character "+c+"is "+count);
        } catch(Exception e){
            System.out.println("I/O Error");
        }
    }
}
4

3 に答える 3

1

これを使って

public static int countOccurance(String inputString, String key) {
    int index = 0;
    int fromIndex = 0;
    int result = 0;

    if (inputString == null || key == null) {
        return 0;
    }

    while ((index = inputString.indexOf(key, fromIndex)) != -1) {
        result++;
        fromIndex = index + key.length;
    }
    return result;
}
于 2012-06-28T06:12:56.460 に答える
1

ループでは、else セクションは必要ありません。

 while(i < str.length()){
     if(str.charAt(i)==c){
         count++;
     } 
     i++;
 }   

Thrustmaster が提案するように、 str!=null を i < str.length() に変更する必要もあります

なぜDataInputStream.readLineを使用しているのか不思議です。非推奨になっていることがわかります。

于 2012-06-28T06:56:37.503 に答える
0

条件は、iまだ文字列の長さ (最後のインデックス + 1) よりも小さいかどうかを確認することです。だから、交換

while(str!=null)

while (i < str.length())
于 2012-06-28T06:13:26.357 に答える