问题描述
有没有办法进一步简化这段代码?这些代码旨在返回给定整数的绝对值。
public class Abs {
public static int abs(int x) {
if(x < 0) { return -x; }
if(x >= 0) { return x; }
assert false;
return 0;
}
}
解决方法
您可以将其放在整数中,并在分配值时检查条件。
int y = x < 0 ? -x : x;
或采用某种方法:
public static int abs(int x) {
return x < 0 ? -x : x;
}
永远不会到达“断言”,因此它是无用的。
,您可以使用ternary operator来简化代码
public class Abs {
public static int abs(int x) {
return x < 0 ? -x : x;
}
}