我只是想知道是否有替代以下操作符的方法:
if (f == 0){
System.out.print("");
} else if (i %2 == 1){
System.out.print("; ");
}更清楚地说,我想要另一种方式来编写if语句的"==“和else if语句的%2 == 1。
谢谢。
发布于 2013-03-13 20:33:05
System.out.print(f!=0 && i%2==1 ? "; " : "");
除了最后一位之外,你可以通过逐位and标记出i的所有位,而不是模数。
i%2的替代方案是i&1。
发布于 2013-03-13 20:40:24
在java 7中,您可以这样比较:
int result = Integer.compare(f, 10);方法说明
public static int compare(int x,
int y)
Compares two int values numerically. The value returned is identical to what would be returned by:
Integer.valueOf(x).compareTo(Integer.valueOf(y))
Parameters:
x - the first int to compare
y - the second int to compare
Returns:
the value 0 if x == y; a value less than 0 if x < y; and a value greater than 0 if x > y
Since: 1.7摘自官方文件
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#compare%28int,%20int%29
而在java 6中
int result = Double.compare(f, 10);方法说明
compare
public static int compare(double d1,
double d2)
Compares the two specified double values. The sign of the integer value returned is the same as that of the integer that would be returned by the call:
new Double(d1).compareTo(new Double(d2))
Parameters:
d1 - the first double to compare
d2 - the second double to compare
Returns:
the value 0 if d1 is numerically equal to d2; a value less than 0 if d1 is numerically less than d2; and a value greater than 0 if d1 is numerically greater than d2.
Since:
1.4摘自官方文档
http://docs.oracle.com/javase/6/docs/api/java/lang/Double.html#compare%28double,%20double%29
你可以根据你的需求使用任何一种方法
我已经测试过这两个了,
请参阅我针对java 6 java 7 的测试解决方案
发布于 2013-03-13 20:37:21
等于运算符==将对象情况下的引用与基元类型情况下的实际值进行比较。
当使用原语类型的包装器对象时,可以用equals(Object obj)替换此运算符。
因此,如果有两个int,a和b,您可以通过以下命令获得它们的包装器:
Integer objA = Integer.valueOf(a);
Integer objB = Integer.valueOf(b);a == b给出了与objA.equals(objB)相同的结果。
https://stackoverflow.com/questions/15385344
复制相似问题