我有一个名为“Thing”的类,它将该类的对象存储在一个arraylist中,我使用for循环来访问它的'字段。
public class Thing {
String title;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
在下面提供的代码中,循环正在访问“Thing”类的对象,一次一个,因此计数总是增加1.如何访问对象的title变量,这样如果标题多次出现相同的“单词”,计数会相应增加吗?
public static String wordCounter(List<Thing> list, String word){
int count = 0;
for(Thing thing : list){
if(thing.getTitle().toLowerCase().contains(word.toLowerCase())){
count++;
}
}
return word + " appears: " + count;
}
由于
答案 0 :(得分:0)
你必须将“标题”拆分为一个arraylist。
List<String> myList = new ArrayList<String>(Arrays.asList(thing.getTitle().toLowerCase().split(" ")));
然后你必须检查这个myList是否包含你的“word”
for(int i=0;i<myList.size();i++){
if(myList.get(i).equals(word.toLowerCasse())){
count++;
}}
答案 1 :(得分:0)
public static int count(String sentence, String word, int times) {
if (sentence.contains(word)) {
times++;
int i = sentence.indexOf(word);
String substring = sentence.substring(i + word.length());
times = count(substring, word, times);
}
return times;
}
public static String wordCounter(List<Thing> list, String word){
int count = 0;
for(Thing thing : list){
count = count(thing.getTitle().toLowerCase(), word.toLowerCase, count);
}
return word + " appears: " + count;
}