【问题标题】:Trying to use break to get out of for loop after getting the desired value - always throwing an exception在获得所需值后尝试使用 break 退出 for 循环 - 总是抛出异常
【发布时间】:2012-12-17 05:09:12
【问题描述】:

我有一个用于遍历数组列表的 for 循环,一旦找到我需要的对象,我想在该对象的 set 方法中设置先前获得的对象,为“未找到”设置一个标志为假,然后跳出循环。之后,如果未找到标志仍然为真,我想抛出异常,否则就到方法的结尾。

我认为我滥用了 break 或 for 循环。我经常抛出异常。

注意,'items' 是 LibraryItems 的数组列表。

        for(LibraryItem l : items) {
        if(l.equals(item)) {
            l.setCheckedOut(patronToRetrieve);
            itemNotFound = false;
            break;
        } else {
            itemNotFound = true;
        }
    }
        if (itemNotFound = true) {
            throw new CheckInOutException("The item " + item.getTitle() + " does not exist in the catalogue. Sorry, " + patronToRetrieve.getName() + ", you will not be able to check this out at this time.");
        } else {

        }

【问题讨论】:

  • 我相信你的意思不是 if (itemNotFound = true) use ==
  • 您是否覆盖了equalshashCode
  • 你不应该为 if 测试做 == 不 =
  • @Matt8541 是的,我是用 = 而不是 == 的假人
  • @Matt8541 itemNotFound 是布尔值,那么为什么要进行双重检查?

标签: java for-loop arraylist


【解决方案1】:

我可以看到的一个问题是:

if (itemNotFound = true) {
            throw new CheckInOutException("The item " + item.getTitle() + " does not exist in the catalogue. Sorry, " + patronToRetrieve.getName() + ", you will not be able to check this out at this time.");
        } 

上面的语句总是产生true,因为你在if子句中将true分配给itemNotFound

应该是:

if (itemNotFound) {
            throw new CheckInOutException("The item " + item.getTitle() + " does not exist in the catalogue. Sorry, " + patronToRetrieve.getName() + ", you will not be able to check this out at this time.");
        } 

(或)

 if (itemNotFound == true) {
                throw new CheckInOutException("The item " + item.getTitle() + " does not exist in the catalogue. Sorry, " + patronToRetrieve.getName() + ", you will not be able to check this out at this time.");
            } 

== 是平等检查,= 是赋值。

【讨论】:

  • 如果 itemNotFound 是一个布尔值,你已经有了 true/fase 的值,那么执行 true==true 是冗余检查,仅此而已。
猜你喜欢
  • 2013-09-28
  • 2012-06-28
  • 2014-01-17
  • 1970-01-01
  • 1970-01-01
  • 2014-01-01
  • 2012-08-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多