Java程序设计中文slide.pptVIP

  • 3
  • 0
  • 约1.2万字
  • 约 67页
  • 2015-12-21 发布于湖北
  • 举报
Java程序设计中文slide.ppt

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Chapter 3 选 择 Objectives 引言   在程序2-2中,半径被赋一个负值,程序会打印一个非法的结果,如果处理这种情况?   Java和所有高级程序设计语言一样也提供选择语句,以便在两个或更多可选择的流程中做出选择。 if (radius0) System.out.println(“Incorrect input”); else{ …… } boolean 数据类型及其运算 通常在一个程序里需要进行两个值的比较,比如,i是否比j大。Java提供六种比较运算符,也称为关系运算符,用于两个值的比较。比较的结果是一个布尔值:true(真)或false(假)。 boolean b = (1 2); 比较运算符 问题: 一个简单的数学学习工具 if 语句 单向if 语句 if (booleanExpression) { statement(s); } Note 警告 在if的子句末尾加分号(;)是常见的错误 if (radius = 0); { area = radius*radius*PI; System.out.println( The area for the circle of radius + radius + is + area); } 这个错误很难被发现,因为它不是一个编译错误或运行错误,而是一个逻辑错误。它相当于条件为真时什么都不做(空语句)。 Simple if Demo 问题: 猜生日 通过询问朋友生日那天属于下面5个数字集合的哪几个,然后将这几个集合的第一个数字相加之和即是生日. 游戏背后的数学基础 1、2、4、8、16对应二进制数1、10、100、1000、10000 19 对应 10011 ,31对应11111 双向if语句 if (booleanExpression) { statement(s)-for-the-true-case; } else { statement(s)-for-the-false-case; } if...else Example if (radius = 0) { area = radius * radius * 3.14159; System.out.println(The area for the “ + “circle of radius + radius + is + area); } else { System.out.println(Negative input); } 嵌套的if语句 Trace if-else statement Trace if-else statement Trace if-else statement Trace if-else statement Trace if-else statement 选择语句中的常见错误 常见错误1:忘记必要的括号. if (radius = 0) area = radius*radius*PI; System.out.println( The area for the circle of radius + radius + is + area); 如果块中只有一条语句,就可以忽略花括号,当需要用花括号将多条语句括在一起时,忘记花括号是一个常见的程序设计错误。 选择语句中的常见错误 常见错误2:在if行出现错误的分号. if (radius = 0); { area = radius*radius*PI; System.out.println( The area for the circle of radius + radius + is + area); } This mistake is hard to find, because it is not a compilation error or a runtime error, it is a logic error. This error often occurs when you use the next-line block style. 选择语句中的常见错误 常见错误3:对布尔值的冗余测试 避免写成: if(even=true) System.out.println(“It is even”); 选择语句中

文档评论(0)

1亿VIP精品文档

相关文档