2017-01-31 5 views
-2

私は、単語のArrayListを通ってその文の平均長さを求める関数の構築を必要とする割り当てを持っています。 私の関数は3つのテストのうち2つを通過します。最後のものは、ArrayListスロット内に存在するため、検索している句読点が削除され、cleanUpという句読点除去関数を使用すると削除されます。説明するのは少し難しいので、コードのすべての関連部分を示します。arrayListsを使用して平均文長を見つける関数

static String cleanUp(String str) { 
    Pattern p = Pattern.compile("(\\W*)(.*?)(\\W*)"); 
    Matcher m = p.matcher(str); 
    m.matches(); 
    return str.substring(m.end(1), m.end(2)).toLowerCase();  
} 

static double averageSentenceLength(ArrayList<String> text) { 
    double sentences = 0; 
    double realLength = 0; 
    boolean doublePunctuation = false; 

    for(int i = 0; i < text.size(); i++){ 
     if(cleanUp(text.get(i)).length() != 0) { 
     realLength++; 
     if(text.get(i).substring(text.get(i).length()-1).equals(".") || 
      text.get(i).substring(text.get(i).length()-1).equals("!") || 
      text.get(i).substring(text.get(i).length()-1).equals("?")) 
      sentences++; 
     } 
    } 
    return realLength/sentences; 
} 

それが通らないことをテスト:

public void testaverageSentenceLength2() { 
    String[] textArray = {"The", "time", "has", "**********************","come,", "the", "Walrus", "said", 
     "To", "talk", "of", "many", "thi-ngs:", "of", "shoes", "-", "and", "ships", "-", "and", "sealing", "wax", ",", 
     "Of", "cabbages;", "and","!#$@", "kings","?", 
     "And", "why", "the", "sea", "is", "boi.ling", "hot;", 
     "and", "whe;ther", "pigs", "have", "win.gs!"}; 
    ArrayList<String> text = new ArrayList<String>(); 
    for (String str : textArray) { 
     text.add(str); 
    }  
    double avg = FindAuthor.averageSentenceLength(text); 
    assertTrue("Average sentence length of the sample should be 17.5 but was "+avg,approx(avg,17.5)); 
} 

問題は、カウントされていない「王」、したがって、平均文の長さの後に疑問符が原因で発生がダブル何であるか、それはすべきさあ。あなたのcleanup()方法で

+0

平均長さを? –

+0

タイトルの意味は? – EJP

+0

@ cricket_007 1文あたりの平均単語数 –

答えて

0

は、str.substring(m.end(1), m.end(2)).toLowerCase()?文字列が処理されるときに、空の文字列を返しているので、あなたのifの本体が実行されることはありません:文章や単語の

if(cleanUp(text.get(i)).length() != 0) { 
    realLength++; 
    if(text.get(i).substring(text.get(i).length()-1).equals(".") || 
     text.get(i).substring(text.get(i).length()-1).equals("!") || 
     text.get(i).substring(text.get(i).length()-1).equals("?")) 
     sentences++; 
} 
関連する問題