java 有没有更好的方法来做if else语句在这个上下文中[关闭]

ibrsph3r  于 2023-04-28  发布在  Java
关注(0)|答案(3)|浏览(118)

已关闭,此问题为opinion-based。目前不接受答复。
**想改善这个问题吗?**更新问题,以便editing this post可以用事实和引用来回答。

5小时前关闭
Improve this question
我有如下的if-else语句:

if (b != 0. && a != 0.) {
    price = (b + a) / 2;
} else if (b == 0. && a! = 0.) {
    price = a;
} else if (a == 0 && b != 0.) {
    price = b;
} else if (b == 0 && a == 0. && LastPrice != 0.) {
    price = LastPrice;
} else {
    price = previous close;
}

这个想法是,
1.如果b & a不等于0,则price =(B + a)/ 2;
1.如果b为0,但a不是,则取a,反之亦然
1.如果ba都是0,但lastPrice不是,则取lastPrice
1.否则我们就采取之前的收盘
但是,我写的方式非常笨拙,有没有更干净的方式来用更好的编码风格来做?
先谢谢你了。

dpiehjr4

dpiehjr41#

这看起来更像人类的推理,因此更清晰(同时对计算机来说没有更高的成本):

if a and b are 0
  if last price is also 0 price = previous close
  else price = last price
else if b is zero /* and therefore at this point a isn't */ price = a
else if a is zero /* and therefore b isn't */ price = b
else /*a and b are nonzero, so */ price = (b+a)/2
9fkzdhlc

9fkzdhlc2#

你可以使用streams来写:

price = DoubleStream.of(a, b)
    .filter(x -> x != 0)
    .average()
    .orElse(LastPrice != 0 ? LastPrice : previousClose)
h5qlskok

h5qlskok3#

下面是一个改进的if-else语句,它删除了一些重复检查。

if (b != 0. && a != 0.) {
  price = (b + a) / 2;
} else if (b == 0.) { //don't need to check a not equal to zero, because if so we would have been in the previous condition.
   price = a;
} else if (a == 0) { // same here
   price = b;
} else if (LastPrice != 0.) { // same here don't need to check that a and b are not null already checked that case on the first line
    price = LastPrice;
} else {
   price = previous close;
}

或者你可以做一些if语句的嵌套

if (b == 0. && a == 0. && LastPrice == 0.) {
    price = previous close;
  } else {
   if (b == 0.) { 
     price = a;
   } else if (a == 0) { 
     price = b;
   } else if { 
     price = LastPrice;
   }
}

相关问题