522B| ock Statements包块) 语句块是由括号括起来的多条语句的集合。 if(t。ta1>MAx) 例如 System. out. println ("Error!!)i errorCount++ 在Java语法中, 任何使用单条语 再如: 句的地方都可以 if(t。ta1>MAK) 使用语句块 System. out. println (Error!!)i errorcount+ti else System. out. println ("Total: t total)i current total*2 JAVA
11 5.2.2 Block Statements(语句块) • 语句块是由括号括起来的多条语句的集合。 • 例如: • 再如: if (total > MAX) { System.out.println ("Error!!"); errorCount++; } if (total > MAX) { System.out.println ("Error!!"); errorCount++; } else { System.out.println ("Total: " + total); current = total*2; } 在Java语法中, 任何使用单条语 句的地方都可以 使用语句块
523条件运算符 语法: condition? expression/: expression2 If the condition is true, expression is evaluated; if it is false, expression2 is evaluated 这是一个具有返回值的 表达式,可以利用返回 For example: 值来进行某些操作。 larger=((numl >num2)? numl: num2) If numl is greater than num2, then numl is assigned to larger; otherwise, num2 is assigned to larger 12 JAVA
12 5.2.3 条件运算符 • 语法: condition ? expression1 : expression2 • If the condition is true, expression1 is evaluated; if it is false, expression2 is evaluated • For example: larger = ((num1 > num2) ? num1 : num2); • If num1 is greater than num2, then num1 is assigned to larger; otherwise, num2 is assigned to larger 这是一个具有返回值的 表达式,可以利用返回 值来进行某些操作
条件运算符 Another example. System. out. printIn( Your change is "+ count (count ==1)? Dime":"Dimes)); If count equals 1, then Dime is printed If count is anything other than 1, then"Dimes is printed JAVA
13 条件运算符 • Another example: System.out.println ("Your change is " + count + ((count == 1) ? "Dime" : "Dimes")); • If count equals 1, then "Dime" is printed • If count is anything other than 1, then "Dimes" is printed
524if语句嵌套 ·在一条语句嵌入另一条语句的情况称为语句的嵌套 可以使程序确定前一个判断的结果之后再做另外的决定。 在一个嵌套的语句中,else子句和它前面最近且未匹 配的if语句相匹配。 ·可以用括号强制改变 sif-else的匹配关系。 ·例如:56。。。。。 JAVA
14 5.2.4 if语句嵌套 • 在一条if语句嵌入另一条if语句的情况称为if语句的嵌套, • 可以使程序确定前一个判断的结果之后再做另外的决定。 • 在一个嵌套的if语句中,else子句和它前面最近且未匹 配的if语句相匹配。 • 可以用括号强制改变if-else的匹配关系。 • 例如:5.6
53 Comparing Data(数据比较) 浮点数只有二进制数位都相等时才相等。 ·浮点数比较:“==”慎用!判断一浮点数相等的方 法是计算两数的绝对值之差和某个误差标准相比较。 if (Math. abs (f1-f2)< TOLERANCE) System. out. println (Essentially equal")i 字符比较: Unicode字符集定义了java中字符的相对 顺序。可用等式和关系运算符比较。 Characters Unicode values数字在大写字 0-948 through57 母之前,大写 A-Z 65 throug 90字母在小写字 97 through 122 母之前。 a-Z 15 JAVA
15 5.3 Comparing Data(数据比较) • 浮点数只有二进制数位都相等时才相等。 • 浮点数比较:“ == ”慎用!判断一浮点数相等的方 法是计算两数的绝对值之差和某个误差标准相比较。 • 字符比较:Unicode字符集定义了java中字符的相对 顺序。可用等式和关系运算符比较。 if (Math.abs(f1 - f2) < TOLERANCE) System.out.println ("Essentially equal"); Characters Unicode Values 0 – 9 48 through 57 A – Z 65 through 90 a – z 97 through 122 数字在大写字 母之前,大写 字母在小写字 母之前