Java仅从循环中返回值
我有一个方法,如果找到,我需要返回一个特定的对象,否则抛出一个异常。所以我写了以下内容:Java仅从循环中返回值,java,methods,Java,Methods,我有一个方法,如果找到,我需要返回一个特定的对象,否则抛出一个异常。所以我写了以下内容: public CustomerDetails findCustomer( String givenID ) throws CustomerNotFoundException{ for(CustomerDetails nextCustomer : customers){ if(givenID == nextCustomer.getCustomerID()){ r
public CustomerDetails findCustomer( String givenID ) throws CustomerNotFoundException{
for(CustomerDetails nextCustomer : customers){
if(givenID == nextCustomer.getCustomerID()){
return nextCustomer;
}else{
throw new CustomerNotFoundException();
}
}
}
但是它需要我在方法的底部添加一个return语句。有没有办法忽略此问题?将代码更改为:
public CustomerDetails findCustomer( String givenID ) throws CustomerNotFoundException{
for(CustomerDetails nextCustomer : customers){
if(givenID == nextCustomer.getCustomerID()){
return nextCustomer;
}
}
throw new CustomerNotFoundException();
}
当循环未执行时(即
customers
为空),它要求您提供方法的有效结果。你必须这样做:
for (CustomerDetails nextCustomer : customers){
if (givenID == nextCustomer.getCustomerID()){
return nextCustomer;
}
}
throw new CustomerNotFoundException();
因为否则,您将在不符合
if
中提供的条件的第一个元素之后抛出异常,如果找到该对象,您可以返回该对象。如果找不到,则在循环结束时抛出异常:
public CustomerDetails findCustomer( String givenID ) throws CustomerNotFoundException{
for(CustomerDetails nextCustomer : customers){
if(givenID.equals(nextCustomer.getCustomerID())){
return nextCustomer;
}
}
throw new CustomerNotFoundException();
}
注意。您可以将
字符串
与=
进行比较。这里您必须使用equals
方法 如果发生意外行为,则应引发异常。失败的搜索不是例外,但很少是常见的原因
出于良好设计的考虑,您不应该抛出异常。相反,您可以扩展调用方法来测试结果是否为空或类似。您只需添加一个
返回方法末尾的代码>。它将无法访问,因此不会引起问题
你也可以在你的环上用一个试扣。如果你想遵循这条路线,这里有一个方便的教程。
如果在循环中找不到客户,则应将异常抛出循环。您还应该使用“.equals”而不是“==”,因为“givenID”是一个对象
public CustomerDetails findCustomer( String givenID ) throws CustomerNotFoundException {
for (CustomerDetails nextCustomer : customers) {
if (givenID.equals(nextCustomer.getCustomerID())){
return nextCustomer;
}
}
throw new CustomerNotFoundException();
}
如果客户
为空,您希望发生什么?如果第一个客户不是您想要的客户,您真的想抛出异常吗?(这就是您当前的代码将要做的……您永远不会进入循环的第二次迭代。)编译器实际上会抱怨customers
集合为空的情况。在这种情况下,既不执行返回
也不执行抛出
。你应该按照下面建议的方法来实现它。谢谢你的评论,只有在阅读了它们之后,我才意识到实现异常是多么愚蠢。这与问题中的逻辑不同。如果没有提供id,它将循环遍历每个客户equals@VishnudevK但这正是OP所寻找的逻辑。这与quesiton中的逻辑不同。如果没有提供id,它将循环遍历每个客户equals@VishnudevK-实际上,OPs的逻辑是错误的。。如果第一个元素与预期id不匹配,他将抛出异常。