【发布时间】:2016-06-17 15:22:46
【问题描述】:
我有以下场景,
一个 String arr[] 作为输入,可以有整数值,null 或空字符串。
(例如){"230",null,"6",""}
现在,
1. 如果 arr 的前两个条目中存在 null 或空字符串,则这是一个无效的场景,不打印任何内容。
2.如果 arr 的最后两个条目中存在 null 或空,并且前两个条目不为 null 且不为空,则打印前两个条目。
(例如)如果 arr[] 是 {"2","77",null,"5"} 输出将是 2,77。
3. 如果 arr[] 中没有条目既不为空也不为空,则检查所有条目是否为数字。如果不打印什么。
现在我的代码是这样的,
simple validation()
{
onlyFirstTwoNotNullOrNotEmpty = false;
if(//Check if first two params are null)
{
//"print nothing" and return
}
else if(check if third **or** fourth param is null)
{
onlyFirstTwoNotNullOrNotEmpty = true; // setting a boolean
}
//Proceed to check empty string
if(//Check if first two params are empty)
{
"print nothing" and return
}
else if(!onlyFirstTwoNotNullOrNotEmpty) //checking if null
{
if(check if third **or** fourth param is empty)
{
onlyFirstTwoNotNullOrNotEmpty = true; // setting a boolean
}
}
//if all values are not null and not empty
//onlyFirstTwoNotNullOrNotEmpty will be still false
String result;
if(onlyFirstTwoNotNullOrNotEmpty )
{
result = checkIfNumeric(0,1); // only first two entries
}
else
{
result = checkIfNumeric(0,arr[arr.length-1]); // for all entries
}
if(!result.equals("success"))
{
return and print nothing
}
if(onlyFirstTwoNotNullOrNotEmpty)
{
print only first two and return;
}
print all entries and return;
}
如何使用更少的 if 和 else 循环更好地优化此代码?通过 lambda 表达式有什么可能吗?
我不想使用第三方 API 对字符串进行 null 或 Empty 检查。
【问题讨论】:
-
我会首先摆脱布尔值并将当它们为真时您采取的动作移动到您设置它们的块中。但这是一个非常不自然的问题,所以如果解决方案看起来也有点不自然,您不必太担心。
-
@AndrewL 对于像
if(//Check if first two param are empty){ "print nothing" and return这样的伪代码,这个问题对于代码审查来说是非常偏离主题的。 -
我没有看到这一点,当我阅读“如何更好地优化此代码”时,我认为他们已经完成了代码。我的错误@200_success
-
如果缩进正确,代码会更容易阅读。
标签: java if-statement optimization