我有一个 for 循环设置,它遍历对象数组中的每个项目。我有一个 if 语句,用于检查某个项目中的值是否与特定的字符串值匹配。如果是这样,我想将其打印到屏幕上。我这样做没有问题。但是,如果循环一直执行而没有找到匹配项,我希望程序打印一条错误消息。我现在将其设置为 if else 语句的方式,如果每个项目不匹配,程序将打印一条错误消息。我想不出只有在循环完成后才能做到这一点的方法。任何指导将不胜感激。
问问题
10583 次
6 回答
1
在您的代码中使用以下模式:
boolean matchFound = false;
for (item: objects) {
if (item.equals(stringValue) {
//print item the same way as you did
matchFound = true;
}
}
if (!matchFound) {
System.out.println("No match found!");
}
于 2013-11-03T19:08:01.993 回答
0
创建一个布尔变量来存储是否找到匹配项。在循环运行之前将其设置为 false,如果在循环中找到匹配项,则将其设置为 true。如果循环结束后仍然为假,则打印错误消息。
于 2013-11-03T19:07:45.050 回答
0
Keppil 和 Little Child 有很好的解决方案,但是让我建议一个重构,使这个问题随着您的规范变化而变得更容易处理。也许矫枉过正。分解算法的步骤。 首先,获取匹配列表。 然后,决定如何处理它们。例如(你最终也想分解这段代码)
ArrayList<T> matches = new ArrayList<T>; // T is your object type, e.g. String
for (T item : myObjects) {
if (item.equals(thingToMatch))
matches.add(item);
}
// 现在,决定如何处理列表...
if (matches.size() > 0) {
for (T t : matches)
// print it here
// but in the future could log them, store in a database, convert to XML, etc...
}
else
System.out.println("no matches were found to " + thingToMatch);
于 2013-11-03T19:58:41.667 回答
0
boolean matchFound = false; // dont be so eager that there is a match
for(String each : lotOfStrings){
if(each.equals(someOtherStrings)){
matchFound = true;
// break; // optionally, you may break out
}
}
if(!matchFound){ // no match found?
System.out.println("Error");
}else{
System.out.println("Found a match");
}
上面的代码片段显示了您如何实现您想要的。
根据 Keppil 的评论
于 2013-11-03T19:08:08.583 回答
0
正如 Keppil 建议的那样,进行了一些优化:
boolean matchFound = false;
for (int i = start; i < max && boolean == false; i++) {
if (foundElement()) {
matchFound = true;
}
}
if (!matchFound) {
log.error = "";
}
或者你可以做
int i = start;
for (; i < max; i++) {
if (foundElement()) {
break;
}
}
if (i == max) {
log.error = "";
}
于 2013-11-03T19:10:12.267 回答
0
如果您不需要匹配的特定对象,那么解决您的问题的最简洁方法是编写一个帮助方法来进行查找。这样我们就可以避免局部变量的赋值和重新赋值,代码变得更加简洁:
boolean find(List<?> list, Object toFind) {
for (Object o : list) if (o.equals(toFind)) return true;
return false;
}
这适用于字符串列表以及任何其他对象。在 main 方法中,您可以编写
System.out.println((find(list, toFind)? "A" : "No") + " match was found");
如果您确实需要所有匹配的对象,那么我会再次推荐一个帮助方法,它返回所有匹配项的列表,以便您以任何其他方式打印或处理:
<T> List<T> getMatches(List<T> list, Object toFind) {
final List<T> ret = new ArrayList<>();
for (T x : list) if (t.equals(toFind)) ret.add(x);
return ret;
}
现在,在调用方法中,您可以拥有
final List<MyType> matches = find(inputList, toFind);
if (matches.isEmpty()) System.out.println("No match was found");
else { ... process the list as needed ... }
于 2013-11-03T20:10:30.913 回答