题:
编写一程序输出一个由若干单词构成的字符串中的最长单词及其长度,若字符串中有多个单词满足条件须将这些单词全部输出。(注:程序书写要规范)
import java.util.*;
class MaxLenWord {
private ArrayList result = new ArrayList();
private int maxLen = 0;
public MaxLenWord(String str) {
int maxlenWordIndex = 0;
String[] strArr = str.split(" ");
for(int i = 1; i < strArr.length; i++) {
if(strArr[i].length()>strArr[maxlenWordIndex].length()) {
maxlenWordIndex = i;
result.clear();
result.add(strArr[i]);
} else if(strArr[i].length()==strArr[maxlenWordIndex].length()) {
maxlenWordIndex = i;
result.add(strArr[i]);
}
}
}
public ArrayList getMaxLenWord() {
return result;
}
public int getMaxlen() {
Iterator it = result.iterator();
if(it.hasNext()) {
maxLen= ((String)it.next()).length();
}
return maxLen;
}
public static void main(String[] args) {
String str= "The indictment said the defendants had collected geographical geographical geographical geographical data
indicating thousands of people would be killed in the chemical blast";
MaxLenWord mlw = new MaxLenWord(str);
ArrayList maxLen = mlw.getMaxLenWord();
Iterator test = maxLen.iterator();
while(test.hasNext()) {
System.out.println((String)test.next());
}
System.out.println(mlw.getMaxlen());
}
}