Java示例登录-缺少返回
我仍然是新手,请你帮我在下面,因为我得到“失踪返回声明”错误Java示例登录-缺少返回,java,arraylist,login,Java,Arraylist,Login,我仍然是新手,请你帮我在下面,因为我得到“失踪返回声明”错误 publicstaticperson登录(arraylistper,字符串密码,int-idit) { 适用于(人/当前人/人) { if(idit==currentPerson.Id) { if(currentPerson.password.equals(password)){ System.out.println(“登录成功!”); 返回人员; } 其他的 {System.out.println(“密码不正确,请重试”); 返回
publicstaticperson登录(arraylistper,字符串密码,int-idit)
{
适用于(人/当前人/人)
{
if(idit==currentPerson.Id)
{
if(currentPerson.password.equals(password)){
System.out.println(“登录成功!”);
返回人员;
}
其他的
{System.out.println(“密码不正确,请重试”);
返回null;
}}
否则{
System.out.println(“未找到用户。请重试”);
返回null;
}
}
}
其中per是我的个人列表。我需要在找到那个人后把他还给他。还有两个案子需要考虑
per
列表为空或空idit
不在列表中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;
}
publicstaticperson登录(arraylistper,字符串密码,int-idit){
//空列表还是空列表
if(per==null | | per.size()==0)
返回null;
适用于(人/当前人/人){
if(idit==currentPerson.Id){
if(currentPerson.password.equals(password)){
System.out.println(“登录成功!”);
返回人员;
}否则{
System.out.println(“密码不正确,请重试”);
返回null;
}
}否则{
System.out.println(“未找到用户。请重试”);
返回null;
}
}
//名单上没有人
返回null;
}
您应该考虑使用<代码> HashMap <代码>而不是<代码> ARAYLISTAB/COD> >保持<代码>人>代码>对象,它将保证同一
人
的人
对象没有重复的人
对象,并启用对具有给定id的人
对象的即时访问。由于currentPerson
可以为空,因此您永远不会进入循环,编译器会给您错误信息
但是,你真的很接近你只需要移动
System.out.println("User not found. Try again");
return null;
在循环之外
现在,您将在第一个Person
上退出循环,如果idit==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;
方法末尾必须有一个return语句。so
返回null代码>就在最后一个括号的正上方。但是返回null将以总是返回null结束?哦,那么返回什么?idk。我只是告诉你应该把它放在哪里如果null不正确,metod需要返回一些东西更改代码以便返回正确的人,注意:返回null并不奇怪,但很常见,在你的情况下,可能没有人登录,登录faliurebe小心你的if-else语句,你将永远不会循环它们所有。。当您返回时,退出循环。。。
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;