【问题标题】:Need a return Statement? - new to coding需要退货声明吗? - 编码新手
【发布时间】:2016-03-14 03:42:56
【问题描述】:

这个想法是拍卖中的不同批次。我知道我需要一个“Lot”类型的返回语句,但我不确定那会是什么。这是我的代码。

public Lot getLot(int lotNumber)
{
    int index = 0;
    boolean found = false;

    while(index < lots.size() && !found) {
        Lot selectedLot = lots.get(index);
        if(selectedLot.getNumber() == lotNumber) {
            found = true;

        }
        else {
            index++;

        }

    }

    if(!found) {
        found = false;

    }

}

【问题讨论】:

  • 你为什么有selectedLot
  • 为什么found 很重要?当你找到它时,只需将它归还,无需继续卡车运输到阵列的末端。如果循环成功终止,则返回 null

标签: java bluej


【解决方案1】:

您可以使用以下代码:

1) 返回带有某个数字的最后一个批次

  public Lot getLot(int lotNumber)
    {
        int index = 0;
        Lot resultLot = null;
        while(index < lots.size() ) {
            Lot selectedLot = lots.get(index);
            if(selectedLot.getNumber() == lotNumber) {
                resultLot = selectedLot;
            }
            else {
                index++;
            }
        }
        return resultLot;
    }

2) 或(返回带有某个编号的第一个批次)

public Lot getLot(int lotNumber)
{
    int index = 0;
    while(index < lots.size() ) {
        Lot selectedLot = lots.get(index);
        if(selectedLot.getNumber() == lotNumber) {
            return selectedLot;
        }
        else {
            index++;
        }
    }
    return null;
}

3) 或(较小的例子)

public Lot getLot(int lotNumber)
{
    for(Lot selectedLot: lots) {
       if(selectedLot.getNumber() == lotNumber) {
            return selectedLot;
        } 
    } 
    return null; 
}

【讨论】:

  • 终于有一个人使用 for 循环而不是 while... +1
【解决方案2】:

你可以做的事情与此类似,如果找到匹配项,它将返回已匹配的 selectedLot,如果未找到匹配项,则返回 null:

public Lot getLot(int lotNumber) {
    int index = 0;

    while(index < lots.size()) {
        Lot selectedLot = lots.get(index);

        if (selectedLot.getNumber() == lotNumber) {
            return selectedLot;
        } else {
            index++;
        }
    }

    return null;
}

【讨论】:

    【解决方案3】:
    public Lot getLot(int lotNumber) {
        int index = 0;
        boolean found = false;
        Lot selectedLot = null; //set initial value to null
    
        while(index < lots.size() && !found) {
          selectedLot = lots.get(index);
          if(selectedLot.getNumber() == lotNumber) {
             found = true;
          }  else {
            index++;
          }
    
        }
        return selectedLot; //You need to return type Lot 
    }
    

    当您说Lot getLot(int lotNumber) 时,您基本上是在说您正在返回一个 Lot 类型的对象,但您永远不会在代码中返回它

    【讨论】:

    • 这样做会给出错误“找不到变量批次”
    • @jjbb93 很抱歉你应该返回变量selectedLot,我更新了它
    • 还有一件事,你的if(!found) { found = false}是多余的,已经设置为false,不需要再设置了
    猜你喜欢
    • 1970-01-01
    • 2012-10-04
    • 2013-07-11
    • 2011-08-10
    • 2013-07-22
    • 2022-11-18
    • 2017-06-06
    • 2016-06-23
    • 2012-01-02
    相关资源
    最近更新 更多