[英]Easy answer needed: returning function that returns null
我有一个函数,它接受一个邮政编码,并根据它所属的范围为其分配一个数字。 如果它不属于其中一个范围,我希望它失败。 我该怎么办?
/**
* Calculates zone number from second zip code
* @param endZip
* @return endZone
*/
public static int endZone(int endZip)
{
int endZone = 0;
//zone 1
if (endZip >= 00001 && endZip <= 6999)
{
endZone = 1;
}
//zone 2
else if (endZip >= 07000 && endZip <= 19999)
{
endZone = 2;
}
//zone 3
else if (endZip >= 20000 && endZip <= 35999)
{
endZone = 3;
}
//zone 4
else if (endZip >= 36000 && endZip <= 62999)
{
endZone = 4;
}
//zone 5
else if (endZip >= 63000 && endZip <= 84999)
{
endZone = 5;
}
//zone 6
else if (endZip >= 85000 && endZip <= 99999)
{
endZone = 6;
}
return endZone;
}
你有几个选择:
如果没有满足任何条件,1。抛出异常。 2.返回一个特定的整数值,你知道这意味着zip无效(例如-1)。 3.而不是使用整数返回类型,为区域创建枚举:
public enum EndZone
{
Zone1,
Zone2,
....
Invalid
}
然后返回EndZone.Invalid如果条件不满足。
如果由于某种原因你绝对想要返回null,那么简单的事情是将返回类型从int切换到Integer对象,与原语不同,它可以为null。
只需将签名更改为:
public static Integer endZone(int endZip)
并初始化为:
Integer endZone = null;
但其他答案真的更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.