Java 在对象字段中循环?
我有一个名为“Thing”的类,将该类的对象存储在arraylist中,我使用for循环访问它的字段Java 在对象字段中循环?,java,Java,我有一个名为“Thing”的类,将该类的对象存储在arraylist中,我使用for循环访问它的字段 public class Thing { String title; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } 在下面提供的代码中,循环访问“Thing”类的
public class Thing {
String title;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
在下面提供的代码中,循环访问“Thing”类的对象,一次一个,因此计数总是递增1。如何访问对象的title变量,以便在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;
对于(事物:列表){
if(thing.getTitle().toLowerCase().contains(word.toLowerCase())){
计数++;
}
}
返回单词+”出现:“+计数;
}
谢谢您必须将“标题”拆分为一个数组列表
List<String> myList = new ArrayList<String>(Arrays.asList(thing.getTitle().toLowerCase().split(" ")));
List myList=newarraylist(Arrays.asList(thing.getTitle().toLowerCase().split(“”));
然后你必须检查这个myList是否包含你的“单词”
for(int i=0;ipublic static int count(字符串句子、字符串单词、int次){
如果(句子包含(单词)){
时代++;
int i=句子索引(单词);
String substring=句子.substring(i+word.length());
次数=计数(子串、字、次数);
}
返回次数;
}
公共静态字符串字计数器(列表,字符串字){
整数计数=0;
对于(事物:列表){
count=count(thing.getTitle().toLowerCase(),word.toLowerCase,count);
}
返回单词+”出现:“+计数;
}
什么是“东西”?必须更具体一些……您好,欢迎来到StackOverflow,这是一个网站,您可以在这里获得有关代码特定问题的帮助。从和什么问题以及哪些问题开始。您可能还想查看。一个“东西”是类事物的一个对象-我知道这不是很好的命名,只是为了演示而已你需要更清楚地知道你想计算什么。现在,你似乎在计算“给定列表中标题包含给定单词的事物的数量”。也许你想计算“给定列表中所有事物的标题中给定单词出现的总次数”?是的,基本上我想计算一个单词在给定事物的标题中出现的次数。getTitle()。例如,如果标题是“this is an example”,如果通过方法传递的单词是“is”,那么计数将是1。好的,我现在有:public static String wordCounter(列表,String word){int count=0;List myList=new ArrayList();for(thing-thing:List){myList=(Arrays.asList(thing.getTitle().toLowerCase().split(“”));if(myList.contains(word.toLowerCase()){count++;}返回word-----但是它仍然说单词“two”只有一个外观,例如,当出现两次“two”谢谢时,有可能对两个字段执行此操作吗?因此我们已经完成了getTitle(),但是如果我们想在getTitle()的同时执行getAuthor(),该怎么办?@JuliaDune您可以这样做。只需创建另一个列表并为循环创建一个
for(int i=0;i<myList.size();i++){
if(myList.get(i).equals(word.toLowerCasse())){
count++;
}}
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;
}