我很难获得正确的输出,因为我不知道 boolean 值在方法中到底如何工作。我有一个数组列表,我正在检查数组列表中是否有重复项,这是我的代码
public void rentOneInstrument(List<Instrument> instrumentList){
String a="";
String b="";
boolean found = false;
for (int j = 0; j < instrumentList.size(); j++) {
a ="";
a = instrumentList.get(j).getName();
for (int i = j+1; i < instrumentList.size(); i++) {
b = instrumentList.get(i).getName();
System.out.println("a" + a + " b" + b);
if(a.equals(b)){
found = true;
}else {
found = false;
}
}
}
if (found) {
System.out.println("duplicate");
}else{
System.out.println("no duplicate");
}
}
这是我的输出
a Cymbals b Drums,..
a Cymbals b Cello,..
a Cymbals b Cymbals,..
a Drums b Cello,..
a Drums b Cymbals,..
a Cello b Cymbals
无重复//当输出中明显存在重复项时,不打印重复项。我该如何纠正这个问题?
编辑..顺便说一句,我只是想要一个输出来打印是否在循环内找到了重复项
最佳答案
if(a.equals(b)){
found = true
}else {
found = false;
}
这是你的问题。这样,只有循环的最后一次迭代才会存储在 found
中。由于您将其初始化为 false
,因此无需在此处再次将其设置为该值。
for (int i = j+1; i < instrumentList.size(); i++) {
b = instrumentList.get(i).getName();
System.out.println("temp1 " + a + " temp2 " + b);
if(a.equals(b)){
found = true;
}
}
或者,当您找到匹配项时,可以使用 break
语句来跳出循环,如下所示:
if(a.equals(b)){
found = true;
break;
}else {
found = false;
}
这样,found
将为 true,并且不会执行其他迭代,而是在循环结束后继续。
关于java - 如何在 JAVA 方法中合并 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30329493/