如何创建IF语句来检查值是否最接近?

时间:2017-04-17 03:29:02

标签: java android if-statement

我有一系列正/负的整数

----0x7fff5d9a99a0     (1
One: 0x7fff5d9a9978    (2
Two: 0x7fff5d9a9970    (3

并且假设我想在程序找到与myNum

最接近的值时显示Toast消息
int[] numbers = new int[10];
numbers[0] = 100;
numbers[1] = -34200;
numbers[2] = 3040;
numbers[3] = 400433;
numbers[4] = 500;
numbers[5] = -100;
numbers[6] = -200;
numbers[7] = 532;
numbers[8] = 6584;
numbers[9] = -945;

这可能吗?如果是这样我怎么能实现呢?

P.S不,我不想使用System.out.println(),因为我打算将IF语句用于其他内容,我只是觉得显示Toast消息是最简单的事情。

1 个答案:

答案 0 :(得分:3)

怎么样:

public static void main(String[] args) {
    int[] numbers = new int[10];
    numbers[0] = 100;
    numbers[1] = -34200;
    numbers[2] = 3040;
    numbers[3] = 400433;
    numbers[4] = 500;
    numbers[5] = -100;
    numbers[6] = -200;
    numbers[7] = 532;
    numbers[8] = 6584;
    numbers[9] = -945;
    int myNum = 600;

    int distance = Math.abs(numbers[0]-myNum);
    int closest = numbers[0];

    for(int i=1;i<numbers.length;i++) {
        int itemDistance = Math.abs(numbers[i]-myNum);
        if(itemDistance < distance) {
            distance=itemDistance;
            closest=numbers[i];
        }
    }

    System.out.println("Closest number is:"+closest+" with distance: "+distance);
}

将打印:

Closest number is:532 with distance: 68

或者,您可以使用stream执行此操作:

int result = Arrays.stream(numbers).reduce((i,j) -> Math.abs(i-myNum) < Math.abs(j-myNum) ? i : j ).getAsInt();

System.out.println(result);

将打印532,就像上一张一样。