【问题标题】:missing the return statement in the if statement which is in the for loop [duplicate]缺少for循环中的if语句中的return语句[重复]
【发布时间】:2018-05-21 01:11:39
【问题描述】:

发生的问题是错误是“缺少返回语句”;我该如何解决这个问题?代码的实际要点是将所有同伴的余额以及余额加在一起,然后看看是否足够放假。 我还声明了另一个名为

的字段变量
private int every1nzBalance;

public boolean checkMoney(Holiday holiday) 
{



    // For each friend i.e in the list

    for(Friend friend:companions)
    {
        if(friend.getMoney()+ balance>=holiday.getPrice())
        {

         System.out.println("You including your friends have sufficient funds to pay for the"+holiday+" holiday.");

         return true;
        }

        else

        {
            System.out.println("Please ensure that you and your friends have sufficient amount of money for the holiday");

            return false;
        }
      }

    }

【问题讨论】:

  • 如果companions 为空并且for 循环甚至不会迭代一次怎么办?应该返回什么值?你是怎么保证的?
  • 顺便说一句,执行return 会将控制流移出您的方法,也会移出您的循环。由于您在两种if/else 情况下都有return,这意味着您将在第一次迭代时退出哪种失败的循环目的。
  • Companions 是空的,直到通过创建对象并使用来自“member”类的指针来填充,该类最初存储数组列表伴随。应该返回的值是一个布尔值,因为它将“成员”余额与同伴相加,然后如果它超过假期成本,则返回 true。

标签: java for-loop if-statement arraylist bluej


【解决方案1】:

这很简单。如果for 没有任何东西可以迭代(比如数组是空的),那么它根本不会执行。最后需要一个默认的 return 语句:

private int every1nzBalance;

public boolean checkMoney(Holiday holiday) {

if(companions == null) return false; //also default return

for(Friend friend : companions)
{
    if(friend.getMoney()+ balance>=holiday.getPrice())
    {

     System.out.println("You including your friends have sufficient funds to pay for the"+holiday+" holiday.");

     return true;
    }

    else

    {
        System.out.println("Please ensure that you and your friends have sufficient amount of money for the holiday");

        return false;
    }
  }
  return  false; //default return
}

【讨论】:

  • 这样访问 Arraylist 同伴是否正确?
  • 我不知道同伴列表是在哪里初始化的,但是只要你将同伴列表作为参数传递或在类中声明它,它就会起作用。
  • 同伴 ArrayList 在同一个类中声明。当我执行代码时,我得到一个空指针错误
  • 表示你没有构造数组。
  • public void storeFriend(Friendfriend) { if(companions == null)companions = new ArrayList();同伴.add(朋友); }