if

浮点数在计算机中常常无法精确表示,并且计算可能出现误差,因此判断浮点数相等正确的方法是利用差值小于某个临界值来判断

public class Main {
    public static void main(String[] args) {
        double x = 1 - 9.0 / 10;
        if (Math.abs(x - 0.1) < 0.00001) {
            System.out.println("x is 0.1");
        } else {
            System.out.println("x is NOT 0.1");
        }
    }
}

判断引用类型相等

判断值类型的变量是否相等,可以使用==运算符。但是,判断引用类型的变量是否相等,==表示“引用是否相等”,或者说,是否指向同一个对象。例如,下面的两个String类型,它们的内容是相同的,但是,分别指向不同的对象,用==判断,结果为false

public class Main {
    public static void main(String[] args) {
        String s1 = "hello";
        String s2 = "HELLO".toLowerCase();
        System.out.println(s1);
        System.out.println(s2);
        if (s1 == s2) {
            System.out.println("s1 == s2");
        } else {
            System.out.println("s1 != s2");
        }
    }
}

要判断引用类型的变量内容是否相等,必须使用equals()方法

public class Main {
    public static void main(String[] args) {
        String s1 = "hello";
        String s2 = "HELLO".toLowerCase();
        System.out.println(s1);
        System.out.println(s2);
        if (s1.equals(s2)) {
            System.out.println("s1 equals s2");
        } else {
            System.out.println("s1 not equals s2");
        }
    }
}

注意:执行语句s1.equals(s2)时,如果变量s1null,会报NullPointerException
要避免NullPointerException错误,可以利用短路运算符&&

public class Main {
    public static void main(String[] args) {
        String s1 = null;
        if (s1 != null && s1.equals("hello")) {
            System.out.println("hello");
        }
    }
}

还可以把一定不是null的对象"hello"放到前面:例如:if ("hello".equals(s)) { ... }

例:计算bmi

import java.util.Scanner;

/**
 * 计算BMI
 */
public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Height (m): ");
        double height = scanner.nextDouble();
        System.out.print("Weight (kg): ");
        double weight = scanner.nextDouble();
        // FIXME:
        double bmi = weight / (height * height);
        // TODO: 打印BMI值及结果
        System.out.printf("BMI:%.2f ", bmi);
        if (bmi >= 32) {
            System.out.println("非常肥胖");
        } else if (bmi >= 28) {
            System.out.println("肥胖");
        } else if (bmi >= 25) {
            System.out.println("过重");
        } else if (bmi >= 18.5) {
            System.out.println("正常");
        } else {
            System.out.println("过轻");
        }
        System.out.printf("You need to lose at least %.2fkg\n", weight - 24 * height * height);
    }
}
THE END
最后修改:2020 年 03 月 04 日 19 : 19
本文链接:https://www.j000e.com/%E6%B5%81%E7%A8%8B%E6%8E%A7%E5%88%B6/ifjudge.html
版权声明:本文『[if判断][浮点型判断][引用类型判断]』为『Joe』原创。著作权归作者所有。
转载说明:[if判断][浮点型判断][引用类型判断] || Joe's Blog』转载许可类型见文末右下角标识。允许规范转载时,转载文章需注明原文出处及地址。
Last modification:March 4, 2020