2015-10-19 57 views
-1

我还是新来的这可以请帮助我在下面,因为我得到“缺少返回声明”错误。Java示例登录 - 缺少返回

public static Person login(ArrayList<Person> per, String password, int idint) 
    { 
     for (Person currentPerson : per) 
       { 
         if (idint == currentPerson.Id) 
         { 
         if (currentPerson.password.equals(password)){ 
          System.out.println("Login Succesfully!"); 
          return currentPerson; 
         } 
         else 
         {System.out.println("Incorrect password. Try again"); 
          return null; 
         }} 
        else { 
         System.out.println("User not found. Try again"); 
         return null; 
        } 
       } 

    } 

其中每个人是我的人数组列表。我需要在找到时返回此人。

+0

您必须在方法结尾有返回语句。所以'返回null;'就在最后一个括号的上方。 – 3kings

+0

但返回null将最终总是返回null? –

+0

哦所以,返回一些东西? IDK的。我只是告诉你该把它放在哪里 – 3kings

回答

0

还有两种情况需要考虑。

  1. per列表为空或空。
  2. idint不在列表中。

您可以覆盖那些2案件只是增加只有两个语句,其他的答案说。

public static Person login(ArrayList<Person> per, String password, int idint) { 
     //null list or empty list 
     if(per == null || per.size() == 0) 
      return null; 
     for (Person currentPerson : per) { 
      if (idint == currentPerson.Id) { 
       if (currentPerson.password.equals(password)) { 
        System.out.println("Login Succesfully!"); 
        return currentPerson; 
       } else { 
        System.out.println("Incorrect password. Try again"); 
        return null; 
       } 
      } else { 
       System.out.println("User not found. Try again"); 
       return null; 
      } 
     } 
     //Person is not present in the list 
     return null; 

    } 

您应该考虑使用HashMap代替ArrayList的保持Person对象,它将保证没有重复的Person对象相同Person并能与给定id的Person对象即时实时访问。

0

编译器给你错误,因为currentPerson可以是空的,因此你永远不会进入循环。

但是,你真的关闭你只需要移动

System.out.println("User not found. Try again"); 
return null; 

圈外,

你现在退出的第一Personif idint == currentPerson.Id循环,你检查密码,然后退出其他你退出...你永远不会循环它们。

 for (Person currentPerson : per) 
      { 
       if (idint == currentPerson.Id) 
       { 
        if (currentPerson.password.equals(password)){ 
         System.out.println("Login Succesfully!"); 
         return currentPerson; 
        } 
        else 
        { 
         System.out.println("Incorrect password. Try again"); 
         return null; 
        } 
       } 

      } 

      System.out.println("User not found. Try again"); 
      return null;