




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)
文檔簡介
1、Chapter 3 Selections1MotivationsIf you assigned a negative value for radius in Listing 2.1, ComputeArea.java, the program would print an invalid result. If the radius is negative, you dont want the program to compute the area. How can you deal with this situation? 2Objectives3To declare boolean type
2、 and write Boolean expressions using comparison operators (3.2).To program AdditionQuiz using Boolean expressions (3.3).To implement selection control using one-way if statements (3.4)To program the GuessBirthday game using one-way if statements (3.5).To implement selection control using two-way if
3、statements (3.6).To implement selection control using nested if statements (3.7).To avoid common errors in if statements (3.8).To program using selection statements for a variety of examples (BMI, ComputeTax, SubtractionQuiz) (3.9-3.11).To generate random numbers using the Math.random() method (3.9)
4、.To combine conditions using logical operators (&, |, and !) (3.12).To program using selection statements with combined conditions (LeapYear, Lottery) (3.13-3.14).To implement selection control using switch statements (3.15).To write expressions using the conditional operator (3.16). To format outpu
5、t using the System.out.printf method and to format strings using the String.format method (3.17). To examine the rules governing operator precedence and associativity (3.18). (GUI) To get user confirmation using confirmation dialogs (3.19).The boolean Type and OperatorsOften in a program you need to
6、 compare two values, such as whether i is greater than j. Java provides six comparison operators (also known as relational operators) that can be used to compare two values. The result of the comparison is a Boolean value: true or false. boolean b = (1 2); 4Comparison Operators5Operator Nameless tha
7、ngreater than=greater than or equal to=equal to!=not equal toProblem: A Simple Math Learning Tool6AdditionQuizRunThis example creates a program to let a first grader practice additions. The program randomly generates two single-digit integers number1 and number2 and displays a question such as “What
8、 is 7 + 9?” to the student. After the student types the answer, the program displays a message to indicate whether the answer is true or false.One-way if Statementsif (boolean-expression) statement(s);7if (radius = 0) area = radius * radius * PI; System.out.println(The area + for the circle of radiu
9、s + radius + is + area);Note8Simple if Demo9SimpleIfDemoRunWrite a program that prompts the user to enter an integer. If the number is a multiple of 5, print HiFive. If the number is divisible by 2, print HiEven.Problem: Guessing BirthdayThe program can guess your birth date. Run to see how it works
10、.10GuessBirthdayMathematics Basis for the Game19 is 10011 in binary. 7 is 111 in binary. 23 is 11101 in binary11The Two-way if Statementif (boolean-expression) statement(s)-for-the-true-case;else statement(s)-for-the-false-case;12if.else Exampleif (radius = 0) area = radius * radius * 3.14159; Syste
11、m.out.println(The area for the “ + “circle of radius + radius + is + area);else System.out.println(Negative input);13Multiple Alternative if Statements14Trace if-else statement15if (score = 90.0) grade = A;else if (score = 80.0) grade = B;else if (score = 70.0) grade = C;else if (score = 60.0) grade
12、 = D;else grade = F;Suppose score is 70.0The condition is falseanimationTrace if-else statement16if (score = 90.0) grade = A;else if (score = 80.0) grade = B;else if (score = 70.0) grade = C;else if (score = 60.0) grade = D;else grade = F;Suppose score is 70.0The condition is falseanimationTrace if-
13、else statement17if (score = 90.0) grade = A;else if (score = 80.0) grade = B;else if (score = 70.0) grade = C;else if (score = 60.0) grade = D;else grade = F;Suppose score is 70.0The condition is trueanimationTrace if-else statement18if (score = 90.0) grade = A;else if (score = 80.0) grade = B;else
14、if (score = 70.0) grade = C;else if (score = 60.0) grade = D;else grade = F;Suppose score is 70.0grade is CanimationTrace if-else statement19if (score = 90.0) grade = A;else if (score = 80.0) grade = B;else if (score = 70.0) grade = C;else if (score = 60.0) grade = D;else grade = F;Suppose score is
15、70.0Exit the if statementanimationNoteThe else clause matches the most recent if clause in the same block. 20Note, cont.Nothing is printed from the preceding statement. To force the else clause to match the first if clause, you must add a pair of braces: int i = 1; int j = 2; int k = 3; if (i j) if
16、(i k) System.out.println(A); else System.out.println(B);This statement prints B.21Common ErrorsAdding a semicolon at the end of an if clause is a common mistake.if (radius = 0); area = radius*radius*PI; System.out.println( The area for the circle of radius + radius + is + area);This mistake is hard
17、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.22WrongTIP23CAUTION24Problem: An Improved Math Learning Tool This example creates a program to teach a first grade child how to learn subtractions. T
18、he program randomly generates two single-digit integers number1 and number2 with number1 number2 and displays a question such as “What is 9 2?” to the student. After the student types the answer in the input dialog box, the program displays a message dialog box to indicate whether the answer is corr
19、ect.25SubtractionQuizProblem: Body Mass Index Body Mass Index (BMI) is a measure of health on weight. It can be calculated by taking your weight in kilograms and dividing by the square of your height in meters. The interpretation of BMI for people 16 years or older is as follows:26ComputeBMIProblem:
20、 Computing TaxesThe US federal personal income tax is calculated based on the filing status and taxable income. There are four filing statuses: single filers, married filing jointly, married filing separately, and head of household. The tax rates for 2009 are shown below.27Marginal Tax RateSingleMar
21、ried Filing Jointly or Qualified Widow(er)Married Filing SeparatelyHead of Household10%$0 $8,350$0 $16,700$0 $8,350$0 $11,95015%$8,351 $33,950$16,701 $67,900$8,351 $33,950$11,951 $45,50025%$33,951 $82,250$67,901 $137,050$33,951 $68,525$45,501 $117,45028%$82,251 $171,550$137,051 $208,850$68,525 $104,
22、425$117,451 $190,20033%$171,551 $372,950$208,851 $372,950$104,426 $186,475$190,201 - $372,95035%$372,951+$372,951+$186,476+$372,951+Problem: Computing Taxes, cont.if (status = 0) / Compute tax for single filerselse if (status = 1) / Compute tax for married file jointlyelse if (status = 2) / Compute
23、tax for married file separatelyelse if (status = 3) / Compute tax for head of householdelse / Display wrong status28ComputeTaxLogical Operators29Operator Name!not&and|orexclusive or Truth Table for Operator !30Truth Table for Operator &31Truth Table for Operator |32Examples33Here is a program that c
24、hecks whether a number is divisible by 2 and 3, whether a number is divisible by 2 or 3, and whether a number is divisible by 2 or 3 but not both:TestBooleanOperatorsRunTruth Table for Operator !34Truth Table for Operator &35Truth Table for Operator |36Truth Table for Operator 37Examples38System.out
25、.println(Is + number + divisible by 2 and 3? + (number % 2 = 0) & (number % 3 = 0);System.out.println(Is + number + divisible by 2 or 3? + (number % 2 = 0) | (number % 3 = 0); System.out.println(Is + number + divisible by 2 or 3, but not both? + (number % 2 = 0) (number % 3 = 0); TestBooleanOperator
26、sRunThe & and | OperatorsSupplement III.B, “The & and | Operators”39Companion WebsiteThe & and | OperatorsIf x is 1, what is x after this expression?(x 1) & (x+ x) & ( 1 x+)How about (1 = x) | (10 x+)?(1 = x) | (10 x+)?40Companion WebsiteProblem: Determining Leap Year?41LeapYearRunThis program first
27、 prompts the user to enter a year as an int value and checks if it is a leap year.A year is a leap year if it is divisible by 4 but not by 100, or it is divisible by 400. (year % 4 = 0 & year % 100 != 0) | (year % 400 = 0)Problem: Lottery Write a program that randomly generates a lottery of a two-di
28、git number, prompts the user to enter a two-digit number, and determines whether the user wins according to the following rule:42LotteryIf the user input matches the lottery in exact order, the award is $10,000.If the user input matches the lottery, the award is $3,000.If one digit in the user input
29、 matches a digit in the lottery, the award is $1,000.switch Statementsswitch (status) case 0: compute taxes for single filers; break; case 1: compute taxes for married file jointly; break; case 2: compute taxes for married file separately; break; case 3: compute taxes for head of household; break; d
30、efault: System.out.println(Errors: invalid status); System.exit(0);43switch Statement Flow Chart44switch Statement Rules45switch (switch-expression) case value1: statement(s)1; break; case value2: statement(s)2; break; case valueN: statement(s)N; break; default: statement(s)-for-default;The switch-e
31、xpression must yield a value of char, byte, short, or int type and must always be enclosed in parentheses.The value1, ., and valueN must have the same data type as the value of the switch-expression. The resulting statements in the case statement are executed when the value in the case statement mat
32、ches the value of the switch-expression. Note that value1, ., and valueN are constant expressions, meaning that they cannot contain variables in the expression, such as 1 + x. switch Statement RulesThe keyword break is optional, but it should be used at the end of each case in order to terminate the
33、 remainder of the switch statement. If the break statement is not present, the next case statement will be executed.46switch (switch-expression) case value1: statement(s)1; break; case value2: statement(s)2; break; case valueN: statement(s)N; break; default: statement(s)-for-default;The default case
34、, which is optional, can be used to perform actions when none of the specified cases matches the switch-expression.The case statements are executed in sequential order, but the order of the cases (including the default case) does not matter. However, it is good programming style to follow the logica
35、l sequence of the cases and place the default case at the end.Trace switch statement47switch (ch) case a: System.out.println(ch); case b: System.out.println(ch); case c: System.out.println(ch); Suppose ch is a: animationTrace switch statement48switch (ch) case a: System.out.println(ch); case b: Syst
36、em.out.println(ch); case c: System.out.println(ch); ch is a: animationTrace switch statement49switch (ch) case a: System.out.println(ch); case b: System.out.println(ch); case c: System.out.println(ch); Execute this lineanimationTrace switch statement50switch (ch) case a: System.out.println(ch); case
37、 b: System.out.println(ch); case c: System.out.println(ch); Execute this lineanimationTrace switch statement51switch (ch) case a: System.out.println(ch); case b: System.out.println(ch); case c: System.out.println(ch); Execute this lineanimationTrace switch statement52switch (ch) case a: System.out.p
38、rintln(ch); case b: System.out.println(ch); case c: System.out.println(ch); Next statement;Execute next statementanimationTrace switch statement53switch (ch) case a: System.out.println(ch); break; case b: System.out.println(ch); break; case c: System.out.println(ch); Suppose ch is a: animationTrace
39、switch statement54switch (ch) case a: System.out.println(ch); break; case b: System.out.println(ch); break; case c: System.out.println(ch); ch is a: animationTrace switch statement55switch (ch) case a: System.out.println(ch); break; case b: System.out.println(ch); break; case c: System.out.println(c
40、h); Execute this lineanimationTrace switch statement56switch (ch) case a: System.out.println(ch); break; case b: System.out.println(ch); break; case c: System.out.println(ch); Execute this lineanimationTrace switch statement57switch (ch) case a: System.out.println(ch); break; case b: System.out.prin
41、tln(ch); break; case c: System.out.println(ch); Next statement;Execute next statementanimationConditional Operatorif (x 0) y = 1else y = -1;is equivalent toy = (x 0) ? 1 : -1;(boolean-expression) ? expression1 : expression2Ternary operatorBinary operatorUnary operator58Conditional Operatorif (num %
42、2 = 0) System.out.println(num + “is even”);else System.out.println(num + “is odd”);System.out.println( (num % 2 = 0)? num + “is even” : num + “is odd”);59Conditional Operator, cont.(boolean-expression) ? exp1 : exp260Formatting Output 61Use the printf statement.System.out.printf(format, items);Where
43、 format is a string that may consist of substrings and format specifiers. A format specifier specifies how an item should be displayed. An item may be a numeric value, character, boolean value, or a string. Each specifier begins with a percent sign. Frequently-Used Specifiers 62Specifier OutputExamp
44、le %b a boolean value true or false %c a character a %d a decimal integer 200 %f a floating-point number 45.460000 %e a number in standard scientific notation 4.556000e+01%s a string Java is cool Operator Precedencevar+, var-+, - (Unary plus and minus), +var,-var(type) Casting! (Not)*, /, % (Multiplication, division, and remainder)+, - (Binary addition and subtraction), , = (Comparison)=, !=; (Equality) (Exclusive OR) & (Conditional AND)
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 門頭裝修保修協(xié)議書
- 集體股權(quán)分紅協(xié)議書
- ktv噪音環(huán)保協(xié)議書
- 飯?zhí)脙?nèi)部轉(zhuǎn)讓協(xié)議書
- 起訴房產(chǎn)分割協(xié)議書
- 共同承包地建房協(xié)議書
- 配件損壞賠償協(xié)議書
- 防汛倉庫整修協(xié)議書
- 婚沒孩子離婚協(xié)議書
- 解除資產(chǎn)合同協(xié)議書
- 計算機(jī)類創(chuàng)業(yè)計劃書
- 第三單元 主題活動三《建筑模型我設(shè)計》(教學(xué)設(shè)計)-2023-2024學(xué)年四年級下冊綜合實踐活動內(nèi)蒙古版
- 糧食工程專業(yè)實習(xí)報告范文
- 2025年高考數(shù)學(xué)復(fù)習(xí)(新高考專用)重難點09極值點偏移與拐點偏移問題【七大題型】特訓(xùn)(學(xué)生版+解析)
- 廣東省華附、省實、廣雅、深中2025屆高三四校聯(lián)考語文試題與答案
- 皮下氣腫治療
- DBJT45-007-2012 廣西壯族自治區(qū)先張法預(yù)應(yīng)力混凝土管樁基礎(chǔ)技術(shù)規(guī)程
- 皮肌炎皮膚護(hù)理查房
- 2025年河北省職業(yè)院校技能大賽工業(yè)互聯(lián)網(wǎng)集成應(yīng)用參考試題庫(含答案)
- 4-6 《竇娥冤》《雷雨》《哈姆雷特》(說課稿)-2024-2025學(xué)年高一語文必修下冊同步備課系列(說課稿+說課稿)(統(tǒng)編版2019)
- 電大《法理學(xué)》期末考試復(fù)習(xí)資料
評論
0/150
提交評論