我有一个方法,如果找到,我需要返回一个特定的对象,否则会抛出一个异常。所以我写了如下:
public CustomerDetails findCustomer( String givenID ) throws CustomerNotFoundException{
for(CustomerDetails nextCustomer : customers){
if(givenID == nextCustomer.getCustomerID()){
return nextCustomer;
}else{
throw new CustomerNotFoundException();
}
}
}但是它要求我在方法的底部添加一个返回语句。有什么办法可以忽略这一点吗?
发布于 2015-02-25 13:26:40
它要求您在没有执行循环(即customers为空)的情况下,从方法中提供一个有效的结果。你必须这样做:
for (CustomerDetails nextCustomer : customers){
if (givenID == nextCustomer.getCustomerID()){
return nextCustomer;
}
}
throw new CustomerNotFoundException();否则,您将在不满足if中提供的条件的第一个元素之后抛出异常。
发布于 2015-02-25 13:26:22
将代码更改为:
public CustomerDetails findCustomer( String givenID ) throws CustomerNotFoundException{
for(CustomerDetails nextCustomer : customers){
if(givenID == nextCustomer.getCustomerID()){
return nextCustomer;
}
}
throw new CustomerNotFoundException();
}发布于 2015-02-25 13:29:05
如果找到对象,可以返回它。如果找不到它,则在循环结束时抛出一个异常:
public CustomerDetails findCustomer( String givenID ) throws CustomerNotFoundException{
for(CustomerDetails nextCustomer : customers){
if(givenID.equals(nextCustomer.getCustomerID())){
return nextCustomer;
}
}
throw new CustomerNotFoundException();
}请注意。您可以将strings与==进行比较。这里您必须使用equals方法!
https://stackoverflow.com/questions/28720182
复制相似问题