失效链接处理 |
最简洁实用的JAVAEE入门开发手册 PDF 下载
本站整理下载:
链接: https://pan.baidu.com/s/1G1P9mS65t0BzHDzdW_yw8g
提取码: viq7
相关截图:
![]() 主要内容:
假设我们期望 90 分或更高为“优秀”上述代码输出的却是“及格”原因是>和>=效果
是不同的。
前面讲过了浮点数在计算机中常常无法精确表示并且计算可能出现误差因此判
断浮点数相等用==判断不靠谱
// 条件判断
----
public class Main {
public static void main(String[] args) {
double x = 1 - 9.0 / 10;
if (x == 0.1) {
System.out.println("x is 0.1");
} else {
System.out.println("x is NOT 0.1");
}
}
}
正确的方法是利用差值小于某个临界值来判断
// 条件判断
----
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");
}
}
}
判断引用类型相等
在 Java 中判断值类型的变量是否相等可以使用==运算符。但是判断引用类型的
变量是否相等==表示“引用是否相等”或者说是否指向同一个对象。例如下面的
两个 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)时如果变量 s1 为 null 会报
NullPointerException
// 条件判断
----
public class Main {
public static void main(String[] args) {
String s1 = null;
if (s1.equals("hello")) {
System.out.println("hello");
}
}
}
要避免 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))
{ ... }。
练习
请用 if ... else 编写一个程序用于计算体质指数 BMI 并打印结果。
BMI = 体重(kg)除以身高(m)的平方
BMI 结果
• 过轻低于 18.5
• 正常 18.5-25
• 过重 25-28
• 肥胖 28-32
• 非常肥胖高于 32
BMI 练习
小结
if ... else 可以做条件判断 else 是可选的
不推荐省略花括号{}
多个 if ... else 串联要特别注意判断顺序
要注意 if 的边界条件
要注意浮点数判断相等不能直接用==运算符
引用类型判断内容相等要使用 equals()注意避免 NullPointerException
|