我正在嘗試使用嵌套循環搜索另一個用戶輸入搜索字詞數組的文本的用戶輸入數組,然後使用它們出現在文本中的次數輸出搜索字詞總文本的百分比。我認爲我在正確的軌道上,我的問題是計數器不重置每次if語句是真實的。我對編程非常陌生 - 所以我可能完全錯誤。以下是整個計劃。如果任何人都可以看一看,並幫我弄清楚我的問題是什麼,我會永遠感激。使用數組搜索字符串數組
public class termFrequency {
public static void main(String[] args) {
String searchTextPeriod, searchTextComma, searchTextApostrophe, searchTextColon, searchTextExclamation,
searchTextQuestion, searchText, searchTerm;
int counter=0, total, searchIndex=0, termIndex=0;
double percentage=0.0;
String [] searchArray, termArray;
searchText = JOptionPane.showInputDialog("Enter a sentence that is at least 20 words long");
//removes some common punctuation from the searchable text
searchTextPeriod = searchText.replace(".", "");
searchTextComma = searchTextPeriod.replace(",", "");
searchTextApostrophe = searchTextComma.replace("'", " ");
searchTextColon = searchTextApostrophe.replace(":", " ");
searchTextExclamation = searchTextColon.replace("!", "");
searchTextQuestion = searchTextExclamation.replace("?", "");
searchArray = searchTextQuestion.split(" "); //splits the sentence and and puts it into an array
total=searchArray.length;
System.out.println("There are " +total +" words in your sentence");
searchTerm = JOptionPane.showInputDialog("Enter your search terms here seperated by a space");
termArray = searchTerm.split(" ");
DecimalFormat two = new DecimalFormat("#0.00");
boolean found = false;
for (termIndex=0; termIndex<termArray.length; termIndex++)
{
for (searchIndex=0; searchIndex<searchArray.length; searchIndex++)
if (termArray[termIndex].equalsIgnoreCase(searchArray[searchIndex]))
{
counter++;
found = true;
percentage= ((double) counter/(double)total) * 100;
}
if (found)
System.out.println("Search word " + "\'" + termArray[termIndex] + "\' is found " +counter +" times. That is "+ two.format(percentage)+"% of the statement.");
else
System.out.println("Search word " + "\'" + termArray[termIndex] + "\' is not found in the statement.");
}
}
}
}
非常感謝喲!對不起,延遲迴應! – mepclu 2012-07-24 15:54:24
@mepclu不客氣。遲到比從未更好;) – 2012-07-24 16:12:29