在if条件判断中需要注意以下几点:
1.当串联多个if时,要注意判断顺序,正确的方式是按照判断范围大到小一次判断,或者改写成从小到大依次判断:
// 从大到小依次判断:
if (n >= 90) {
// ...
} else if (n >= 60) {
// ...
} else {
// ...
}
// 从小到大依次判断:
if (n < 60) {
// ...
} else if (n < 90) {
// ...
} else {
// ...
}
错误的判断顺序:
public class Main {
public static void main(String[] args) {
int n = 100;
if (n >= 60) {
System.out.println("及格了");
} else if (n >= 90) {
System.out.println("优秀");
} else {
System.out.println("挂科了");
}
}
}
2.浮点数不能精确的表示,并且计算可能出现误差,所以判断浮点数相等用==是不行的,正确的方式是利用差值小于临界值来判断:
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");
}
}
}
3.判断引用类型相等时,“==”表示的是两个引用类型指向同一个对象,而判断内容是否相同就需要使用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");
}
}
}