首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JAVA等于Alternative

JAVA等于Alternative
EN

Stack Overflow用户
提问于 2013-03-13 20:27:53
回答 3查看 1.4K关注 0票数 0

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

代码语言:javascript
复制
if (f == 0){
    System.out.print("");
} else if (i %2 == 1){
    System.out.print("; ");
}

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

谢谢。

EN

回答 3

Stack Overflow用户

发布于 2013-03-13 20:33:05

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

除了最后一位之外,你可以通过逐位and标记出i的所有位,而不是模数。

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

票数 1
EN

Stack Overflow用户

发布于 2013-03-13 20:40:24

在java 7中,您可以这样比较:

代码语言:javascript
复制
int result = Integer.compare(f, 10);

方法说明

代码语言:javascript
复制
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中

代码语言:javascript
复制
int result = Double.compare(f, 10);

方法说明

代码语言:javascript
复制
 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 的测试解决方案

票数 1
EN

Stack Overflow用户

发布于 2013-03-13 20:37:21

等于运算符==将对象情况下的引用与基元类型情况下的实际值进行比较。

当使用原语类型的包装器对象时,可以用equals(Object obj)替换此运算符。

因此,如果有两个intab,您可以通过以下命令获得它们的包装器:

代码语言:javascript
复制
Integer objA = Integer.valueOf(a);
Integer objB = Integer.valueOf(b);

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15385344

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档