JAVA等于替代品

时间:2013-03-13 12:27:53

标签: java operators

我只是想知道是否有以下运营商的替代方案:

if (f == 0){
    System.out.print("");
} else if (i %2 == 1){
    System.out.print("; ");
}

为了更清楚,我想要另一种方法来编写if语句的“==”和else if语句的%2 == 1

感谢。

3 个答案:

答案 0 :(得分:1)

System.out.print(f!=0 && i%2==1 ? "; " : "");

除了模数,你可以用一个按位标记除了最后一个之外的所有位。

i%2的替代方案是i&1

答案 1 :(得分:1)

在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

采取fropm官方文档

http://docs.oracle.com/javase/6/docs/api/java/lang/Double.html#compare%28double,%20double%29

您可以根据自己的要求使用任何方法

我测试过它们

查看我的测试解决方案 for java 6 http://ideone.com/56dm1T 对于java 7 http://ideone.com/mEjt6W

答案 2 :(得分:0)

等于运算符==在基本类型的情况下比较对象和实际值的引用。

使用equals(Object obj)替换此运算符的方案是使用基元类型的包装器对象时。

所以,如果有两个intab,那么你可以获得它们的包装:

Integer objA = Integer.valueOf(a);
Integer objB = Integer.valueOf(b);

a == b提供与objA.equals(objB)相同的结果。