2012-06-28 4 views
-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; 
} 
+0

첫 번째 'i ++'는 관계가 없습니다. – trutheality

+0

디버거를 사용해 보셨습니까? –

답변

0

조건이 i 있는지 확인하는 것입니다

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"); 
     } 
    } 
} 
1

사용은 여전히 ​​(마지막 인덱스 + 1) 문자열의 길이보다 작습니다. 그래서, 루프에서

while (i < str.length()) 
0

while(str!=null) 

교체, 당신은 다른 섹션이 필요하지 않습니다.

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

는 STR을 변경해야합니다! = 난에 널 (null) < str.length()를 사용하면 DataInputStream.readLine를 사용하는 이유

그냥 궁금 트러스트 마스터

에 의해 제안. 나는 그것이 더 이상 사용되지 않는 것을 본다.

관련 문제