为什么我的Java ArrayList未输出预期结果,该如何排查解决?
问题原因与解决方案
你的代码存在3处核心错误,共同导致了运行结果不符合预期:
- 第一处:
listContains方法遍历逻辑错误
你在循环里写了else break,意味着只要第一个元素和目标值不相等,就会直接终止遍历,只有第一个元素23能被正确匹配,后续的34、45、56都永远不会被遍历到。 - 第二处:没有接收
listContains方法的返回值
你调用listContains(4)、listContains(56)后,完全没有接收方法返回的布尔结果,反而手动把numberFound设为了false,方法的执行结果被直接丢弃了。 - 第三处:if判断误用赋值运算符代替比较运算符
if (numberFound = true)里的=是赋值操作,这行代码会直接把numberFound设为true,再判断值,所以不管实际查找结果如何,判断分支永远走“找到”的逻辑。
修复后的代码
1. 修正listContains方法
// returns a true or a false value indicating if a number provided to it is present in an ArrayList private static boolean listContains(int param1) { boolean found = false; for (int x: listOfNumbers) { if (param1 == x) { found = true; // 找到后直接终止循环,不需要继续遍历 break; } // 不匹配的情况继续循环,不要break } return found; }
2. 修正main方法逻辑
boolean numberFound = false; addTestData(); System.out.println("*** Testing ArrayList Search ***"); System.out.println("I am going to test if the number 4 is in the ArrayList."); // 接收方法返回值 numberFound = listContains(4); // 布尔值直接判断即可,不需要和true比较 if (numberFound) System.out.println("The number 4 was found."); else System.out.println("The number 4 was not found."); System.out.println(""); // 测试56不需要重复调用addTestData,数据已经初始化过了 System.out.println("I am going to test if the number 56 is in the ArrayList"); numberFound = listContains(56); if (numberFound) System.out.println("The number 56 was found."); else System.out.println("The number 56 was not found.");
内容的提问来源于stack exchange,提问作者ryanmonty42
相关产品推荐
相关产品推荐

