2015-02-06 4 views
-1

코드는 거의 옳은 것 같습니다. 내가 얻을 대답은 3.0이지만 그것은 2.6.I 있어야합니다. 나는/다른 stackoverflow 답변을 봤어 봤어하지만 난 수정이 필요가 없습니다. 2 시간 동안이 오류를 시도했습니다.문장 내 단어의 평균 길이를 구하십시오. Java

코드 :

public class Sentence { // words holds the array. 
private static String[] words = {"hi","my","name","is","Bob"}; 
} 

public String toString() { //Returns the array into Strings. 
    return Arrays.toString(words); 
} 

    public double meanLength(String s) { 
    String wordysplit[] = toString().split(", "); 
    float numWords = wordysplit.length; 
    float totalChar = 0; 
    for (int i = 0; i < numWords; i++) { 
     totalChar += wordysplit[i].length(); 

    } 
    return (totalChar/numWords); 
}  

public static void main(String[] args) // Really simplified this code to make it 
cleaner for you guys 
System.out.println("Mean word length:"+words.meanLength()); 

     } 
} 

모든 도움을 주셔서 감사합니다. 감사. 여기

+0

'float numWords = wordysplit.length * 1.0;','totalChar + = wordysplit [i] .length() * 1.0;'및'return ((totalChar/numWords) * 1.0;' – npinti

+0

문장 클래스를 끝내는 중괄호가 있음을 알아 두십시오. 당신이 원하는 것 같지 않습니다. – alephtwo

+0

@alephtwo 그래, 미안, 실수 였어. – bob9123

답변

1

StringUtils 것을이

String resultString = StringUtils.join(words, ""); 
float avg = (float)resultString.length()/words.length; 

참고를하는 쉬운 방법이 Apache 공용 클래스입니다.

http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html

프로젝트에 Apache commons를 추가하지 않으려면

는, 당신은 당신의 배열에서 String을 만들려면이 간단한 알고리즘을 사용할 수 있습니다

String[] array = {"AB", "B", "C"}; 
StringBuilder builder = new StringBuilder(); 
for(String s : array) { 
    builder.append(s); 
} 

System.out.println((float)builder.toString().length()/array.length); 

avg1.3333334를 인쇄겠습니까.

+0

Join (Java.util.Collection, String)은 Java에 StringUtils를 적용 할 수 없다고 말한다. lang.String []). 가져온 항목을 가져온 후 com.sun.deploy.util.StringUtils; – bob9123

+0

다른 방법을 시도해보십시오. – bob9123

+0

배열에 고정 된 양의 요소가 없으므로 해당 코드를 사용할 수 없습니다. 그들은 항상 변합니다. 따라서 6 개 이상의 요소가 작동하면 "/ 3"을 사용할지 모르겠습니다. – bob9123

관련 문제