0

我只是想知道是否有以下运算符的替代方法:

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

更清楚地说,我想要另一种编写 if 语句的 "==" 和 else if 语句的方法%2 == 1

谢谢。

4

3 回答 3

1

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

除了模数之外,您可以通过位与标记除最后一位之外的 i 的所有位。

的替代方案i%2i&1

于 2013-03-13T12:33:04.763 回答
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

取自官方文档

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

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

我已经测试了他们两个

请参阅我为 java 6 http://ideone.com/56dm1T测试的解决方案, 用于 java 7 http://ideone.com/mEjt6W

于 2013-03-13T12:40:23.513 回答
0

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

可以替换此运算符的一种情况equals(Object obj)是使用原始类型的包装器对象时。

因此,如果有两个int,ab, 并且您通过以下方式获得它们的包装器:

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

a == b给出与 相同的结果objA.equals(objB)

于 2013-03-13T12:37:20.663 回答