JHTP小结_第五章_控制语句Part 2-逻辑运算符

来源:互联网 发布:github tensorflow 编辑:程序博客网 时间:2024/05/20 08:00


Chapter 5 Control Statements: Part 2; Logical Operators

Summary

Section 5.2Essentials of Counter-Controlled Repetition

• Counter-controlledrepetition (p. 153) requires a control variable, the initial value of thecontrol variable, the increment by which the control variable is modified eachtime through the loop (also known as each iteration of the loop) and theloop-continuation condition that determines whether looping should continue.

• You can declare avariable and initialize it in the same statement.

Section 5.3forRepetitionStatement

• Thewhilestatement canbe used to implement any counter-controlled loop.

• Theforstatement (p.155) specifies all the details of counter-controlled repetition in its header

• When theforstatementbegins executing, its control variable is declared and initialized. If the loop-continuationcondition is initially true, the body executes. After executing the loop’sbody, the increment expression executes. Then the loop-continuation test isperformed again to determine whether the program should continue with the nextiteration of the loop.

• The general format oftheforstatement isfor(initialization;loopContinuationCondition;increment)statement where theinitializationexpressionnames the loop’s control variable and provides its initial value,loopContinuationConditiondetermineswhether the loop should continue executing andincrement modifies thecontrol variable’s value, so that the loop-continuation condition eventuallybecomes false. The two semicolons in theforheader arerequired.

• Mostforstatementscan be represented with equivalentwhilestatements asfollows:

initialization;

while(loopContinuationCondition)

{

statement

increment;

}

• Typically,forstatementsare used for counter-controlled repetition andwhilestatementsfor sentinel-controlled repetition.

• If theinitializationexpression intheforheader declares the control variable, the control variable canbe used only in thatforstatement—it will not exist outside theforstatement.

• The expressions in aforheader areoptional. If theloopContinuationConditionis omitted, Java assumesthat it’s always true, thus creating an infinite loop. You might omit theinitializationexpression ifthe control variable is initialized before the loop. You might omit theincrementexpression ifthe increment is calculated with statements in the loop’s body or if noincrement is needed.

• The incrementexpression in aforacts as if it’s a standalone statement at the end of thefor’s body.

• Aforstatement cancount downward by using a negative increment—i.e., a decrement (p. 158).

• If theloop-continuation condition is initiallyfalse, theforstatement’sbody does not execute.

Section 5.4Examples Using theforStatement

• Java treatsfloating-point constants like1000.0and0.05as typedouble. Similarly,Java treats whole-number constants like7and-22as typeint.

• The format specifier%4soutputs aStringin a fieldwidth (p. 161) of 4—that is,printfdisplays the value withat least 4 character positions. If the value to be output is less than 4character positions wide, the value is right justified (p. 161) in the field bydefault. If the value is greater than 4 character positions wide, the fieldwidth expands to accommodate the appropriate number of characters. To leftjustify (p. 161) the value, use a negative integer to specify the field width.

Math.pow(x,y)(p. 162)calculates the value ofxraised to theythpower. The method receives twodoublearguments andreturns adoublevalue.

• The comma (,) formattingflag (p. 162) in a format specifier indicates that a floating-point value shouldbe output with a grouping separator (p. 162). The actual separator used isspecific to the user’s locale (i.e., country). In the United States, the numberwill have commas separating every three digits and a decimal point separatingthe fractional part of the number, as in 1,234.45.

• The.in a formatspecifier indicates that the integer to its right is the number’s precision.

Section 5.5dowhileRepetition Statement

• Thedowhilestatement (p.163) is similar to thewhilestatement. In thewhile, the programtests the loop-continuation condition at the beginning of the loop, beforeexecuting its body; if the condition is false, the body never executes. Thedowhilestatementtests the loop-continuation conditionafterexecuting theloop’s body; therefore, the body always executes at least once.

Section 5.6switchMultiple-Selection Statement

• Theswitchstatement (p.165) performs different actions based on the possible values of a constant integralexpression (a constant value of typebyte,short,intorchar, but notlong), or aString.

• The end-of-fileindicator is a system-dependent keystroke combination that terminates userinput.

On UNIX/Linux/Mac OS Xsystems, end-of-file is entered by typing the sequence<Ctrl>don a line byitself. This notation means to simultaneously press both theCtrlkey and thedkey.

On Windows systems, enterend-of-file by typing<Ctrl> z.

ScannermethodhasNext(p. 168)determines whether there’s more data to input. This method returns thebooleanvaluetrueif there’smore data; otherwise, it returnsfalse. As long asthe end-of-file indicator has not been typed, method hasNextwill returntrue.

• Theswitchstatementconsists of a block that contains a sequence ofcaselabels (p.168) and an optionaldefaultcase (p. 168).

• In aswitch, the programevaluates the controlling expression and compares its value with each caselabel. If amatch occurs, the program executes the statements for thatcase.

• Listing casesconsecutively with no statements between them enables the cases to perform the sameset of statements.

• Every value you wish totest in aswitchmust be listed in a separatecaselabel.

• Eachcasecan havemultiple statements, and these need not be placed in braces.

• Acase’s statementstypically end with abreakstatement (p. 168) that terminates theswitch’s execution.

• Withoutbreakstatements,each time a match occurs in theswitch, the statements for thatcase and subsequent cases execute until a breakstatement orthe end of theswitchis encountered.

• If no match occursbetween the controlling expression’s value and acaselabel, theoptionaldefaultcase executes. If no match occurs and theswitchdoes notcontain adefaultcase, program control simply continues with the first statementafter theswitch.

Section 5.7 ClassAutoPolicyCase Study:Strings inswitchStatements

Strings can be usedin aswitchstatement’s controlling expression andcaselabels.

Section 5.8breakandcontinueStatements

• Thebreakstatement,when executed in awhile,for,dowhileorswitch, causes immediate exit from that statement.

• Thecontinuestatement (p.174), when executed in awhile,forordowhile, skips the loop’s remaining body statements and proceeds withits next iteration. Inwhileanddowhilestatements, the program evaluates the loop-continuation testimmediately. In aforstatement, the increment expression executes, then the programevaluates the loop-continuation test.

Section 5.9Logical Operators

• Simple conditions areexpressed in terms of the relational operators>,<,>=and<=and theequality operators==and!=, and each expression tests only one condition.

• Logical operators (p.176) enable you to form more complex conditions by combining simple conditions.

The logical operators are&&(conditional AND),||(conditionalOR),&(boolean logical

AND),|(booleanlogical inclusive OR),^(boolean logical exclusive OR) and!(logicalNOT).

• To ensure that twoconditions arebothtrue, use the&&(conditional AND)operator. If either or both of the simple conditions are false, the entireexpression is false.

• To ensure that eitherorboth of twoconditions are true, use the||(conditional OR)operator, which evaluates to true if either or both of its simple conditionsare true.

Self-Review Exercises

• A condition using&&or||operators (p. 176) uses short-circuit evaluation (p. 178)—they’reevaluated only until it’s known whether the condition is true or false.

• The&and|operators (p.178) work identically to the&&and||operators butalways evaluate both operands.

• A simple conditioncontaining the boolean logical exclusive OR (^; p. 179)operator is trueif and only if one of its operands istrueand the other isfalse. If bothoperands aretrueor both arefalse,the entirecondition isfalse. This operator is also guaranteed to evaluate both of itsoperands.

• The unary!(logical NOT;p. 179) operator “reverses” the value of a condition.

0 0