1
Java_4B – Control Structures: Part 2
Outline4.9 Essentials of Counter-Controlled Repetition4.10 for Repetition Statement4.11 Examples Using the for Statement4.12 do…while Repetition Statement4.13 switch Multiple-Selection Statement4.14 break and continue Statements4.15 Logical Operators4.16 Structured Programming Summary
2
4.9 Essentials of Counter-Controlled Repetition
• Counter-controlled repetition requires:– Control variable (loop counter)
– Initial value of the control variable
– Increment/decrement of control variable through each loop
– Condition that tests for the final value of the control variable
Outline3
// // // // CounterCounterCounterCounter----controlledcontrolledcontrolledcontrolled repetitionrepetitionrepetitionrepetition withwithwithwith thethethethe whilewhilewhilewhile repetitionrepetitionrepetitionrepetition statementstatementstatementstatement....
public public public public classclassclassclass WhileCounterWhileCounterWhileCounterWhileCounter
{{{{
public static public static public static public static voidvoidvoidvoid mainmainmainmain( ( ( ( StringStringStringString argsargsargsargs[] ) [] ) [] ) [] )
{ { { {
intintintint countercountercountercounter = 1; // = 1; // = 1; // = 1; // declaredeclaredeclaredeclare andandandand initializeinitializeinitializeinitialize controlcontrolcontrolcontrol variablevariablevariablevariable
whilewhilewhilewhile ( ( ( ( countercountercountercounter <= 10 ) // <= 10 ) // <= 10 ) // <= 10 ) // looplooplooploop----continuationcontinuationcontinuationcontinuation conditionconditionconditioncondition
{{{{
SystemSystemSystemSystem....outoutoutout....printfprintfprintfprintf( "%d ", ( "%d ", ( "%d ", ( "%d ", countercountercountercounter ););););
++++++++countercountercountercounter; // ; // ; // ; // incrementincrementincrementincrement controlcontrolcontrolcontrol variablevariablevariablevariable by 1by 1by 1by 1
} // } // } // } // endendendend whilewhilewhilewhile
SystemSystemSystemSystem....outoutoutout....printlnprintlnprintlnprintln(); // (); // (); // (); // outputoutputoutputoutput a a a a newlinenewlinenewlinenewline
} // } // } // } // endendendend mainmainmainmain
} // } // } // } // endendendend classclassclassclass WhileCounterWhileCounterWhileCounterWhileCounter
1 2 3 4 5 6 7 8 9 101 2 3 4 5 6 7 8 9 101 2 3 4 5 6 7 8 9 101 2 3 4 5 6 7 8 9 10
4
4.10 for Repetition Statement
• Handles counter-controlled-repetition details
Outline5
// // // // CounterCounterCounterCounter----controlledcontrolledcontrolledcontrolled repetitionrepetitionrepetitionrepetition withwithwithwith thethethethe forforforfor repetitionrepetitionrepetitionrepetition statementstatementstatementstatement....
public public public public classclassclassclass ForCounterForCounterForCounterForCounter
{{{{
public static public static public static public static voidvoidvoidvoid mainmainmainmain( ( ( ( StringStringStringString argsargsargsargs[] ) [] ) [] ) [] )
{{{{
// // // // forforforfor statementstatementstatementstatement headerheaderheaderheader includesincludesincludesincludes initializationinitializationinitializationinitialization, , , ,
// // // // looplooplooploop----continuationcontinuationcontinuationcontinuation conditionconditionconditioncondition andandandand incrementincrementincrementincrement
forforforfor ( ( ( ( intintintint countercountercountercounter = 1; = 1; = 1; = 1; countercountercountercounter <= 10; <= 10; <= 10; <= 10; countercountercountercounter++ ) ++ ) ++ ) ++ )
SystemSystemSystemSystem....outoutoutout....printfprintfprintfprintf( "%d ", ( "%d ", ( "%d ", ( "%d ", countercountercountercounter ););););
SystemSystemSystemSystem....outoutoutout....printlnprintlnprintlnprintln(); // (); // (); // (); // outputoutputoutputoutput a a a a newlinenewlinenewlinenewline
} // } // } // } // endendendend mainmainmainmain
} // } // } // } // endendendend classclassclassclass ForCounterForCounterForCounterForCounter
1 2 3 4 5 6 7 8 9 101 2 3 4 5 6 7 8 9 101 2 3 4 5 6 7 8 9 101 2 3 4 5 6 7 8 9 10
6
Fig. 4.3 for statement header components.
for ( int counter = 1; counter <= 10; counter++ )
Increment of control variable
Control variable
Final value of control variable for which the condition is true
forkeyword
Loop-continuation condition
Initial value of control variable
Required semicolon separator
Required semicolon separator
7
4.10 for Repetition Structure (cont.)
for ( initialization; loopContinuationCondition; increment )statement;
can usually be rewritten as:
initialization;while ( loopContinuationCondition )))) {{{{
statement;increment;
}
8
Fig. 4.4 for statement activity diagram.
[counter <= 10]
[counter > 10]
int counter = 1
counter++Determine whether the final value of control variable has been reached
g.drawLine( 10, 10, 250, counter * 10 );
Establish initial value of control variable
Draw a line on the applet
Increment the control variable
9
4.11 Examples Using the for Statement
• Varying control variable in for statement– Vary control variable from 1 to 100 in increments of 1
• for ( int i = 1; i <= 100; i++ )
– Vary control variable from 100 to 1 in increments of –1• for ( int i = 100; i >= 1; i-- )
– Vary control variable from 7 to 77 in increments of 7• for ( int i = 7; i <= 77; i += 7 )
Outline10
// Summing integers with the for statement.// Summing integers with the for statement.// Summing integers with the for statement.// Summing integers with the for statement.
public class Sum public class Sum public class Sum public class Sum
{{{{
public static void main( String public static void main( String public static void main( String public static void main( String argsargsargsargs[] )[] )[] )[] )
{{{{
intintintint total = 0; // initialize totaltotal = 0; // initialize totaltotal = 0; // initialize totaltotal = 0; // initialize total
// total even integers from 2 through 20// total even integers from 2 through 20// total even integers from 2 through 20// total even integers from 2 through 20
for ( for ( for ( for ( intintintint number = 2; number <= 20; number += 2 )number = 2; number <= 20; number += 2 )number = 2; number <= 20; number += 2 )number = 2; number <= 20; number += 2 )
total += number;total += number;total += number;total += number;
System.out.printfSystem.out.printfSystem.out.printfSystem.out.printf( "Sum is %( "Sum is %( "Sum is %( "Sum is %dddd\\\\nnnn", total ); // display results", total ); // display results", total ); // display results", total ); // display results
} // end main} // end main} // end main} // end main
} // end class Sum} // end class Sum} // end class Sum} // end class Sum
Sum is 110Sum is 110Sum is 110Sum is 110
11
Compound Interest Calculation
• A person invest $1.000 in a savings account yielding 5% interest. Assuming that all the interest is left on deposit, calculate and print the amount of money in the account at the end of each year for 10 years. Use the following formula to determine the amount:a = p(1 + r)n
where– p is the original amount invested
– r is annual interest rate
– n is number of years
– a is amount on deposit at the end of the nth year
Outline12
// Compound// Compound// Compound// Compound----interest calculations with for.interest calculations with for.interest calculations with for.interest calculations with for.
public class Interest public class Interest public class Interest public class Interest
{{{{
public static void main( String public static void main( String public static void main( String public static void main( String argsargsargsargs[] )[] )[] )[] )
{{{{
double amount; // amount on deposit at end of each yeardouble amount; // amount on deposit at end of each yeardouble amount; // amount on deposit at end of each yeardouble amount; // amount on deposit at end of each year
double principal = 1000.0; // initial amount before interedouble principal = 1000.0; // initial amount before interedouble principal = 1000.0; // initial amount before interedouble principal = 1000.0; // initial amount before interestststst
double rate = 0.05; // interest ratedouble rate = 0.05; // interest ratedouble rate = 0.05; // interest ratedouble rate = 0.05; // interest rate
// display headers// display headers// display headers// display headers
System.out.printfSystem.out.printfSystem.out.printfSystem.out.printf( "%s%20s( "%s%20s( "%s%20s( "%s%20s\\\\n", "Year", "Amount on deposit" );n", "Year", "Amount on deposit" );n", "Year", "Amount on deposit" );n", "Year", "Amount on deposit" );
// calculate amount on deposit for each of ten years// calculate amount on deposit for each of ten years// calculate amount on deposit for each of ten years// calculate amount on deposit for each of ten years
for ( for ( for ( for ( intintintint year = 1; year <= 10; year++ ) year = 1; year <= 10; year++ ) year = 1; year <= 10; year++ ) year = 1; year <= 10; year++ )
{{{{
// calculate new amount for specified year// calculate new amount for specified year// calculate new amount for specified year// calculate new amount for specified year
amount = principal * amount = principal * amount = principal * amount = principal * Math.powMath.powMath.powMath.pow( 1.0 + rate, year );( 1.0 + rate, year );( 1.0 + rate, year );( 1.0 + rate, year );
// display the year and the amount// display the year and the amount// display the year and the amount// display the year and the amount
System.out.printfSystem.out.printfSystem.out.printfSystem.out.printf( "%4d%,20.2f( "%4d%,20.2f( "%4d%,20.2f( "%4d%,20.2f\\\\n", year, amount );n", year, amount );n", year, amount );n", year, amount );
} // end for} // end for} // end for} // end for
} // end main} // end main} // end main} // end main
} // end class Interest} // end class Interest} // end class Interest} // end class Interest
Outline13
Year Amount on depositYear Amount on depositYear Amount on depositYear Amount on deposit
1 1,050.001 1,050.001 1,050.001 1,050.00
2 1,102.502 1,102.502 1,102.502 1,102.50
3 1,157.633 1,157.633 1,157.633 1,157.63
4 1,215.514 1,215.514 1,215.514 1,215.51
5 1,276.285 1,276.285 1,276.285 1,276.28
6 1,340.106 1,340.106 1,340.106 1,340.10
7 1,407.107 1,407.107 1,407.107 1,407.10
8 1,477.468 1,477.468 1,477.468 1,477.46
9 1,551.339 1,551.339 1,551.339 1,551.33
10 1,628.8910 1,628.8910 1,628.8910 1,628.89
14
4.12 do…while Repetition Statement
• do…while structure– Similar to while structure
– Tests loop-continuation after performing body of loop• i.e., loop body always executes at least once
Outline15
// do...// do...// do...// do...whilewhilewhilewhile repetitionrepetitionrepetitionrepetition statementstatementstatementstatement....
public public public public classclassclassclass DoWhileTestDoWhileTestDoWhileTestDoWhileTest
{ { { {
public static public static public static public static voidvoidvoidvoid mainmainmainmain( ( ( ( StringStringStringString argsargsargsargs[] )[] )[] )[] )
{{{{
intintintint countercountercountercounter = 1; // = 1; // = 1; // = 1; // initializeinitializeinitializeinitialize countercountercountercounter
do do do do
{{{{
SystemSystemSystemSystem....outoutoutout....printfprintfprintfprintf( "%d ", ( "%d ", ( "%d ", ( "%d ", countercountercountercounter ););););
++++++++countercountercountercounter;;;;
} } } } whilewhilewhilewhile ( ( ( ( countercountercountercounter <= 10 ); // <= 10 ); // <= 10 ); // <= 10 ); // endendendend do...do...do...do...whilewhilewhilewhile
SystemSystemSystemSystem....outoutoutout....printlnprintlnprintlnprintln(); // (); // (); // (); // outputsoutputsoutputsoutputs a a a a newlinenewlinenewlinenewline
} // } // } // } // endendendend mainmainmainmain
} // } // } // } // endendendend classclassclassclass DoWhileTestDoWhileTestDoWhileTestDoWhileTest
1 2 3 4 5 6 7 8 9 101 2 3 4 5 6 7 8 9 101 2 3 4 5 6 7 8 9 101 2 3 4 5 6 7 8 9 10
16
Fig. 4.8 do…while repetition statement activity diagram.
action state
[true]
[false]
condition
17
4.13 switch Multiple-Selection Statement
• switch statement– Used for multiple selections
Outline18
// // // // GradeBookGradeBookGradeBookGradeBook class uses switch statement to count A, B, C, D and F grades.class uses switch statement to count A, B, C, D and F grades.class uses switch statement to count A, B, C, D and F grades.class uses switch statement to count A, B, C, D and F grades.
import import import import java.util.Scannerjava.util.Scannerjava.util.Scannerjava.util.Scanner; // program uses class Scanner; // program uses class Scanner; // program uses class Scanner; // program uses class Scanner
public class public class public class public class GradeBookGradeBookGradeBookGradeBook
{{{{
private String private String private String private String courseNamecourseNamecourseNamecourseName; // name of course this ; // name of course this ; // name of course this ; // name of course this GradeBookGradeBookGradeBookGradeBook representsrepresentsrepresentsrepresents
private private private private intintintint total; // sum of gradestotal; // sum of gradestotal; // sum of gradestotal; // sum of grades
private private private private intintintint gradeCountergradeCountergradeCountergradeCounter; // number of grades entered; // number of grades entered; // number of grades entered; // number of grades entered
private private private private intintintint aCountaCountaCountaCount; // count of A grades; // count of A grades; // count of A grades; // count of A grades
private private private private intintintint bCountbCountbCountbCount; // count of B grades; // count of B grades; // count of B grades; // count of B grades
private private private private intintintint cCountcCountcCountcCount; // count of C grades; // count of C grades; // count of C grades; // count of C grades
private private private private intintintint dCountdCountdCountdCount; // count of D grades; // count of D grades; // count of D grades; // count of D grades
private private private private intintintint fCountfCountfCountfCount; // count of F grades; // count of F grades; // count of F grades; // count of F grades
// constructor initializes // constructor initializes // constructor initializes // constructor initializes courseNamecourseNamecourseNamecourseName; ; ; ;
// // // // intintintint instance variables are initialized to 0 by defaultinstance variables are initialized to 0 by defaultinstance variables are initialized to 0 by defaultinstance variables are initialized to 0 by default
public public public public GradeBookGradeBookGradeBookGradeBook( String name )( String name )( String name )( String name )
{{{{
courseNamecourseNamecourseNamecourseName = name; // initializes = name; // initializes = name; // initializes = name; // initializes courseNamecourseNamecourseNamecourseName
} // end constructor} // end constructor} // end constructor} // end constructor
// method to set the course name// method to set the course name// method to set the course name// method to set the course name
public void public void public void public void setCourseNamesetCourseNamesetCourseNamesetCourseName( String name )( String name )( String name )( String name )
{{{{
courseNamecourseNamecourseNamecourseName = name; // store the course name= name; // store the course name= name; // store the course name= name; // store the course name
} // end method } // end method } // end method } // end method setCourseNamesetCourseNamesetCourseNamesetCourseName
Outline19
// // // // methodmethodmethodmethod to to to to retrieveretrieveretrieveretrieve thethethethe coursecoursecoursecourse namenamenamename
public public public public StringStringStringString getCourseNamegetCourseNamegetCourseNamegetCourseName()()()()
{{{{
returnreturnreturnreturn courseNamecourseNamecourseNamecourseName;;;;
} // } // } // } // endendendend methodmethodmethodmethod getCourseNamegetCourseNamegetCourseNamegetCourseName
// display a // display a // display a // display a welcomewelcomewelcomewelcome messagemessagemessagemessage to to to to thethethethe GradeBookGradeBookGradeBookGradeBook useruseruseruser
public public public public voidvoidvoidvoid displayMessagedisplayMessagedisplayMessagedisplayMessage()()()()
{{{{
// // // // getCourseNamegetCourseNamegetCourseNamegetCourseName getsgetsgetsgets thethethethe namenamenamename ofofofof thethethethe coursecoursecoursecourse
SystemSystemSystemSystem....outoutoutout....printfprintfprintfprintf( "( "( "( "WelcomeWelcomeWelcomeWelcome to to to to thethethethe grade grade grade grade bookbookbookbook forforforfor\\\\n%s!n%s!n%s!n%s!\\\\nnnn\\\\n", n", n", n",
getCourseNamegetCourseNamegetCourseNamegetCourseName() );() );() );() );
} // } // } // } // endendendend methodmethodmethodmethod displayMessagedisplayMessagedisplayMessagedisplayMessage
// // // // inputinputinputinput arbitraryarbitraryarbitraryarbitrary numbernumbernumbernumber ofofofof gradesgradesgradesgrades fromfromfromfrom useruseruseruser
public public public public voidvoidvoidvoid inputGradesinputGradesinputGradesinputGrades()()()()
{{{{
Scanner Scanner Scanner Scanner inputinputinputinput = = = = newnewnewnew Scanner( Scanner( Scanner( Scanner( SystemSystemSystemSystem.in );.in );.in );.in );
intintintint grade; // grade grade; // grade grade; // grade grade; // grade enteredenteredenteredentered by by by by useruseruseruser
SystemSystemSystemSystem....outoutoutout....printfprintfprintfprintf( "%s( "%s( "%s( "%s\\\\n%sn%sn%sn%s\\\\n %sn %sn %sn %s\\\\n %sn %sn %sn %s\\\\n", n", n", n",
""""EnterEnterEnterEnter thethethethe integerintegerintegerinteger gradesgradesgradesgrades in in in in thethethethe rangerangerangerange 0000----100.", 100.", 100.", 100.",
"Type "Type "Type "Type thethethethe endendendend----ofofofof----filefilefilefile indicatorindicatorindicatorindicator to to to to terminateterminateterminateterminate inputinputinputinput:", :", :", :",
"On UNIX/Linux/Mac OS X type <"On UNIX/Linux/Mac OS X type <"On UNIX/Linux/Mac OS X type <"On UNIX/Linux/Mac OS X type <ctrlctrlctrlctrl> d > d > d > d thenthenthenthen presspresspresspress EnterEnterEnterEnter",",",",
"On Windows type <"On Windows type <"On Windows type <"On Windows type <ctrlctrlctrlctrl> z > z > z > z thenthenthenthen presspresspresspress EnterEnterEnterEnter" );" );" );" );
Outline20
// loop until user enters the end// loop until user enters the end// loop until user enters the end// loop until user enters the end----ofofofof----file indicatorfile indicatorfile indicatorfile indicator
while ( while ( while ( while ( input.hasNextinput.hasNextinput.hasNextinput.hasNext() ) () ) () ) () )
{{{{
grade = grade = grade = grade = input.nextIntinput.nextIntinput.nextIntinput.nextInt(); // read grade(); // read grade(); // read grade(); // read grade
total += grade; // add grade to totaltotal += grade; // add grade to totaltotal += grade; // add grade to totaltotal += grade; // add grade to total
++++++++gradeCountergradeCountergradeCountergradeCounter; // increment number of grades; // increment number of grades; // increment number of grades; // increment number of grades
// call method to increment appropriate counter// call method to increment appropriate counter// call method to increment appropriate counter// call method to increment appropriate counter
incrementLetterGradeCounterincrementLetterGradeCounterincrementLetterGradeCounterincrementLetterGradeCounter( grade );( grade );( grade );( grade );
} // end while } // end while } // end while } // end while
} // end method } // end method } // end method } // end method inputGradesinputGradesinputGradesinputGrades
// add 1 to appropriate counter for specified grade// add 1 to appropriate counter for specified grade// add 1 to appropriate counter for specified grade// add 1 to appropriate counter for specified grade
public void public void public void public void incrementLetterGradeCounterincrementLetterGradeCounterincrementLetterGradeCounterincrementLetterGradeCounter( ( ( ( intintintint grade )grade )grade )grade )
{{{{
// determine which grade was entered// determine which grade was entered// determine which grade was entered// determine which grade was entered
switch ( grade / 10 )switch ( grade / 10 )switch ( grade / 10 )switch ( grade / 10 )
{ { { {
case 9: // grade was between 90case 9: // grade was between 90case 9: // grade was between 90case 9: // grade was between 90
case 10: // and 100 case 10: // and 100 case 10: // and 100 case 10: // and 100
++++++++aCountaCountaCountaCount; // increment ; // increment ; // increment ; // increment aCountaCountaCountaCount
break; // necessary to exit switchbreak; // necessary to exit switchbreak; // necessary to exit switchbreak; // necessary to exit switch
case 8: // grade was between 80 and 89case 8: // grade was between 80 and 89case 8: // grade was between 80 and 89case 8: // grade was between 80 and 89
++++++++bCountbCountbCountbCount; // increment ; // increment ; // increment ; // increment bCountbCountbCountbCount
break; // exit switchbreak; // exit switchbreak; // exit switchbreak; // exit switch
Outline21
casecasecasecase 7: // grade 7: // grade 7: // grade 7: // grade waswaswaswas betweenbetweenbetweenbetween 70 70 70 70 andandandand 79797979
++++++++cCountcCountcCountcCount; // ; // ; // ; // incrementincrementincrementincrement cCountcCountcCountcCount
breakbreakbreakbreak; // exit ; // exit ; // exit ; // exit switchswitchswitchswitch
casecasecasecase 6: // grade 6: // grade 6: // grade 6: // grade waswaswaswas betweenbetweenbetweenbetween 60 60 60 60 andandandand 69696969
++++++++dCountdCountdCountdCount; // ; // ; // ; // incrementincrementincrementincrement dCountdCountdCountdCount
breakbreakbreakbreak; // exit ; // exit ; // exit ; // exit switchswitchswitchswitch
default: // grade default: // grade default: // grade default: // grade waswaswaswas lesslesslessless thanthanthanthan 60606060
++++++++fCountfCountfCountfCount; // ; // ; // ; // incrementincrementincrementincrement fCountfCountfCountfCount
breakbreakbreakbreak; // ; // ; // ; // optionaloptionaloptionaloptional; ; ; ; willwillwillwill exit exit exit exit switchswitchswitchswitch anywayanywayanywayanyway
} // } // } // } // endendendend switchswitchswitchswitch
} // } // } // } // endendendend methodmethodmethodmethod incrementLetterGradeCounterincrementLetterGradeCounterincrementLetterGradeCounterincrementLetterGradeCounter
// display a report // display a report // display a report // display a report basedbasedbasedbased on on on on thethethethe gradesgradesgradesgrades enteredenteredenteredentered by by by by useruseruseruser
public public public public voidvoidvoidvoid displayGradeReportdisplayGradeReportdisplayGradeReportdisplayGradeReport()()()()
{{{{
SystemSystemSystemSystem....outoutoutout....printlnprintlnprintlnprintln( "( "( "( "\\\\nGradenGradenGradenGrade Report:" );Report:" );Report:" );Report:" );
Outline22
// if user entered at least one grade...// if user entered at least one grade...// if user entered at least one grade...// if user entered at least one grade...
if ( if ( if ( if ( gradeCountergradeCountergradeCountergradeCounter != 0 ) != 0 ) != 0 ) != 0 )
{{{{
// calculate average of all grades entered// calculate average of all grades entered// calculate average of all grades entered// calculate average of all grades entered
double average = (double) total / double average = (double) total / double average = (double) total / double average = (double) total / gradeCountergradeCountergradeCountergradeCounter; ; ; ;
// output summary of results// output summary of results// output summary of results// output summary of results
System.out.printfSystem.out.printfSystem.out.printfSystem.out.printf( "Total of the %d grades entered is %( "Total of the %d grades entered is %( "Total of the %d grades entered is %( "Total of the %d grades entered is %dddd\\\\nnnn", ", ", ",
gradeCountergradeCountergradeCountergradeCounter, total );, total );, total );, total );
System.out.printfSystem.out.printfSystem.out.printfSystem.out.printf( "Class average is %.2f( "Class average is %.2f( "Class average is %.2f( "Class average is %.2f\\\\n", average );n", average );n", average );n", average );
System.out.printfSystem.out.printfSystem.out.printfSystem.out.printf( "%( "%( "%( "%ssss\\\\n%s%dn%s%dn%s%dn%s%d\\\\n%s%dn%s%dn%s%dn%s%d\\\\n%s%dn%s%dn%s%dn%s%d\\\\n%s%dn%s%dn%s%dn%s%d\\\\n%s%dn%s%dn%s%dn%s%d\\\\nnnn", ", ", ",
"Number of students who received each grade:", "Number of students who received each grade:", "Number of students who received each grade:", "Number of students who received each grade:",
"A: ", "A: ", "A: ", "A: ", aCountaCountaCountaCount, // display number of A grades, // display number of A grades, // display number of A grades, // display number of A grades
"B: ", "B: ", "B: ", "B: ", bCountbCountbCountbCount, // display number of B grades, // display number of B grades, // display number of B grades, // display number of B grades
"C: ", "C: ", "C: ", "C: ", cCountcCountcCountcCount, // display number of C grades , // display number of C grades , // display number of C grades , // display number of C grades
"D: ", "D: ", "D: ", "D: ", dCountdCountdCountdCount, // display number of D grades, // display number of D grades, // display number of D grades, // display number of D grades
"F: ", "F: ", "F: ", "F: ", fCountfCountfCountfCount ); // display number of F grades); // display number of F grades); // display number of F grades); // display number of F grades
} // end if} // end if} // end if} // end if
else // no grades were entered, so output appropriate messelse // no grades were entered, so output appropriate messelse // no grades were entered, so output appropriate messelse // no grades were entered, so output appropriate messageageageage
System.out.printlnSystem.out.printlnSystem.out.printlnSystem.out.println( "No grades were entered" );( "No grades were entered" );( "No grades were entered" );( "No grades were entered" );
} // end method } // end method } // end method } // end method displayGradeReportdisplayGradeReportdisplayGradeReportdisplayGradeReport
} // end class } // end class } // end class } // end class GradeBookGradeBookGradeBookGradeBook
Outline23
// // // // CreateCreateCreateCreate GradeBookGradeBookGradeBookGradeBook objectobjectobjectobject, , , , inputinputinputinput gradesgradesgradesgrades andandandand display grade report.display grade report.display grade report.display grade report.
public public public public classclassclassclass GradeBookTestGradeBookTestGradeBookTestGradeBookTest
{{{{
public static public static public static public static voidvoidvoidvoid mainmainmainmain( ( ( ( StringStringStringString argsargsargsargs[] )[] )[] )[] )
{{{{
// // // // createcreatecreatecreate GradeBookGradeBookGradeBookGradeBook objectobjectobjectobject myGradeBookmyGradeBookmyGradeBookmyGradeBook andandandand
// // // // passpasspasspass coursecoursecoursecourse namenamenamename to to to to constructorconstructorconstructorconstructor
GradeBookGradeBookGradeBookGradeBook myGradeBookmyGradeBookmyGradeBookmyGradeBook = = = = newnewnewnew GradeBookGradeBookGradeBookGradeBook( ( ( (
"CS101 "CS101 "CS101 "CS101 IntroductionIntroductionIntroductionIntroduction to Java to Java to Java to Java ProgrammingProgrammingProgrammingProgramming" );" );" );" );
myGradeBookmyGradeBookmyGradeBookmyGradeBook....displayMessagedisplayMessagedisplayMessagedisplayMessage(); // display (); // display (); // display (); // display welcomewelcomewelcomewelcome messagemessagemessagemessage
myGradeBookmyGradeBookmyGradeBookmyGradeBook....inputGradesinputGradesinputGradesinputGrades(); // (); // (); // (); // readreadreadread gradesgradesgradesgrades fromfromfromfrom useruseruseruser
myGradeBookmyGradeBookmyGradeBookmyGradeBook....displayGradeReportdisplayGradeReportdisplayGradeReportdisplayGradeReport(); // display report (); // display report (); // display report (); // display report basedbasedbasedbased on on on on gradesgradesgradesgrades
} // } // } // } // endendendend mainmainmainmain
} // } // } // } // endendendend classclassclassclass GradeBookTestGradeBookTestGradeBookTestGradeBookTest
Outline24
Welcome to the grade book forWelcome to the grade book forWelcome to the grade book forWelcome to the grade book for
CS101 Introduction to Java Programming!CS101 Introduction to Java Programming!CS101 Introduction to Java Programming!CS101 Introduction to Java Programming!
Enter the integer grades in the range 0Enter the integer grades in the range 0Enter the integer grades in the range 0Enter the integer grades in the range 0----100.100.100.100.
Type the endType the endType the endType the end----ofofofof----file indicator to terminate input:file indicator to terminate input:file indicator to terminate input:file indicator to terminate input:
On UNIX/Linux/Mac OS X type <ctrl> d then press On UNIX/Linux/Mac OS X type <ctrl> d then press On UNIX/Linux/Mac OS X type <ctrl> d then press On UNIX/Linux/Mac OS X type <ctrl> d then press EnteEnteEnteEnte
On Windows type <ctrl> z then press EnterOn Windows type <ctrl> z then press EnterOn Windows type <ctrl> z then press EnterOn Windows type <ctrl> z then press Enter
99999999
92929292
45454545
57575757
63636363
71717171
76767676
85858585
90909090
100100100100
^Z^Z^Z^Z
Grade Report:Grade Report:Grade Report:Grade Report:
Total of the 10 grades entered is 778Total of the 10 grades entered is 778Total of the 10 grades entered is 778Total of the 10 grades entered is 778
Class average is 77,80Class average is 77,80Class average is 77,80Class average is 77,80
Number of students who received each grade:Number of students who received each grade:Number of students who received each grade:Number of students who received each grade:
A: 4A: 4A: 4A: 4
B: 1B: 1B: 1B: 1
C: 2C: 2C: 2C: 2
D: 1D: 1D: 1D: 1
F: 2F: 2F: 2F: 2
25
Fig. 4.10 switch multiple-selection statement activity diagram with break statements.
case a action(s) break
default action(s)
[true]
case b action(s) break
case z action(s) break
.
.
.
[false]
case a
[true]
[true]
case b
case z
[false]
[false]
26
4.14 break and continue Statements
• break/continue– Alter flow of control
• break statement – Causes immediate exit from control structure
• Used in while, for, do…while or switch statements
• continue statement – Skips remaining statements in loop body
– Proceeds to next iteration• Used in while, for or do…while statements
Outline27
// break statement exiting a for statement.// break statement exiting a for statement.// break statement exiting a for statement.// break statement exiting a for statement.
public class public class public class public class BreakTestBreakTestBreakTestBreakTest
{{{{
public static void main( String public static void main( String public static void main( String public static void main( String argsargsargsargs[] )[] )[] )[] )
{{{{
intintintint count; // control variable also used after loop terminatescount; // control variable also used after loop terminatescount; // control variable also used after loop terminatescount; // control variable also used after loop terminates
for ( count = 1; count <= 10; count++ ) // loop 10 timesfor ( count = 1; count <= 10; count++ ) // loop 10 timesfor ( count = 1; count <= 10; count++ ) // loop 10 timesfor ( count = 1; count <= 10; count++ ) // loop 10 times
{ { { {
if ( count == 5 ) // if count is 5, if ( count == 5 ) // if count is 5, if ( count == 5 ) // if count is 5, if ( count == 5 ) // if count is 5,
break; // terminate loopbreak; // terminate loopbreak; // terminate loopbreak; // terminate loop
System.out.printfSystem.out.printfSystem.out.printfSystem.out.printf( "%d ", count );( "%d ", count );( "%d ", count );( "%d ", count );
} // end for} // end for} // end for} // end for
System.out.printfSystem.out.printfSystem.out.printfSystem.out.printf( "( "( "( "\\\\nBrokenBrokenBrokenBroke out of loop at count = %out of loop at count = %out of loop at count = %out of loop at count = %dddd\\\\nnnn", count );", count );", count );", count );
} // end main} // end main} // end main} // end main
} // end class } // end class } // end class } // end class BreakTestBreakTestBreakTestBreakTest
1 2 3 41 2 3 41 2 3 41 2 3 4
Broke out of loop at count = 5Broke out of loop at count = 5Broke out of loop at count = 5Broke out of loop at count = 5
Outline28
// continue statement terminating an iteration of a for statemen// continue statement terminating an iteration of a for statemen// continue statement terminating an iteration of a for statemen// continue statement terminating an iteration of a for statement.t.t.t.
public class public class public class public class ContinueTestContinueTestContinueTestContinueTest
{{{{
public static void main( String public static void main( String public static void main( String public static void main( String argsargsargsargs[] )[] )[] )[] )
{{{{
for ( for ( for ( for ( intintintint count = 1; count <= 10; count++ ) // loop 10 timescount = 1; count <= 10; count++ ) // loop 10 timescount = 1; count <= 10; count++ ) // loop 10 timescount = 1; count <= 10; count++ ) // loop 10 times
{ { { {
if ( count == 5 ) // if count is 5, if ( count == 5 ) // if count is 5, if ( count == 5 ) // if count is 5, if ( count == 5 ) // if count is 5,
continue; // skip remaining code in loopcontinue; // skip remaining code in loopcontinue; // skip remaining code in loopcontinue; // skip remaining code in loop
System.out.printfSystem.out.printfSystem.out.printfSystem.out.printf( "%d ", count );( "%d ", count );( "%d ", count );( "%d ", count );
} // end for} // end for} // end for} // end for
System.out.printlnSystem.out.printlnSystem.out.printlnSystem.out.println( "( "( "( "\\\\nUsednUsednUsednUsed continue to skip printing 5" );continue to skip printing 5" );continue to skip printing 5" );continue to skip printing 5" );
} // end main} // end main} // end main} // end main
} // end class } // end class } // end class } // end class ContinueTestContinueTestContinueTestContinueTest
1 2 3 41 2 3 41 2 3 41 2 3 4
Broke out of loop at count = 5Broke out of loop at count = 5Broke out of loop at count = 5Broke out of loop at count = 5
29
4.15 Logical Operators
• Logical operators– Allows for forming more complex conditions
– Combines simple conditions
• Java logical operators– && (conditional AND)
– & (boolean logical AND)
– || (conditional OR)
– | (boolean logical inclusive OR)
– ^ (boolean logical exclusive OR)
– ! (logical NOT)
30
4.15 Logical Operators
• if (gender == FEMALE && age >= 65 )++seniorFemales;
• possible notation:if ((gender == FEMALE ) && ( age>= 65))
++seniorFemales;
• short-circuit evaluation of complex condition (not all parts of condition are evaluated each time; first part of condition is evaluated each time and the result may be known
• & and | evaluated each time both parts of the condition
31
expression1 expression2 expression1 &&&&&&&& expression2
false false false
false true false true false false true true true Fig. 4.15 &&&&&&&& (conditional AND) operator truth table.
expression1 expression2 expression1 ||||||||expression2
false false false
false true truetrue false true
true true trueFig. 4.16 |||||||| (conditional OR) operator truth table.
32
expression1 expression2 expression1 ^̂̂̂ expression2
false false false
false true true true false true true true false Fig. 4.17 ^̂̂̂ (boolean logical exclusive OR) operator truth table.
expression !!!!expressionfalse true
true falseFig. 4.18 !!!! (logical negation, or logical NOT) operator truth table.
Outline33
// // // // LogicalLogicalLogicalLogical operatorsoperatorsoperatorsoperators....
public public public public classclassclassclass LogicalOperatorsLogicalOperatorsLogicalOperatorsLogicalOperators
{{{{
public static public static public static public static voidvoidvoidvoid mainmainmainmain( ( ( ( StringStringStringString argsargsargsargs[] )[] )[] )[] )
{{{{
// // // // createcreatecreatecreate truthtruthtruthtruth table table table table forforforfor && (&& (&& (&& (conditionalconditionalconditionalconditional AND) AND) AND) AND) operatoroperatoroperatoroperator
SystemSystemSystemSystem....outoutoutout....printfprintfprintfprintf( "%s( "%s( "%s( "%s\\\\n%s: %bn%s: %bn%s: %bn%s: %b\\\\n%s: %bn%s: %bn%s: %bn%s: %b\\\\n%s: %bn%s: %bn%s: %bn%s: %b\\\\n%s: %bn%s: %bn%s: %bn%s: %b\\\\nnnn\\\\n",n",n",n",
""""ConditionalConditionalConditionalConditional AND (&&)", "AND (&&)", "AND (&&)", "AND (&&)", "falsefalsefalsefalse && && && && falsefalsefalsefalse", ( ", ( ", ( ", ( falsefalsefalsefalse && && && && falsefalsefalsefalse ),),),),
""""falsefalsefalsefalse && && && && truetruetruetrue", ( ", ( ", ( ", ( falsefalsefalsefalse && && && && truetruetruetrue ), ), ), ),
""""truetruetruetrue && && && && falsefalsefalsefalse", ( ", ( ", ( ", ( truetruetruetrue && && && && falsefalsefalsefalse ),),),),
""""truetruetruetrue && && && && truetruetruetrue", ( ", ( ", ( ", ( truetruetruetrue && && && && truetruetruetrue ) );) );) );) );
// // // // createcreatecreatecreate truthtruthtruthtruth table table table table forforforfor || (|| (|| (|| (conditionalconditionalconditionalconditional OR) OR) OR) OR) operatoroperatoroperatoroperator
SystemSystemSystemSystem....outoutoutout....printfprintfprintfprintf( "%s( "%s( "%s( "%s\\\\n%s: %bn%s: %bn%s: %bn%s: %b\\\\n%s: %bn%s: %bn%s: %bn%s: %b\\\\n%s: %bn%s: %bn%s: %bn%s: %b\\\\n%s: %bn%s: %bn%s: %bn%s: %b\\\\nnnn\\\\n",n",n",n",
""""ConditionalConditionalConditionalConditional OR (||)", "OR (||)", "OR (||)", "OR (||)", "falsefalsefalsefalse || || || || falsefalsefalsefalse", ( ", ( ", ( ", ( falsefalsefalsefalse || || || || falsefalsefalsefalse ),),),),
""""falsefalsefalsefalse || || || || truetruetruetrue", ( ", ( ", ( ", ( falsefalsefalsefalse || || || || truetruetruetrue ),),),),
""""truetruetruetrue || || || || falsefalsefalsefalse", ( ", ( ", ( ", ( truetruetruetrue || || || || falsefalsefalsefalse ),),),),
""""truetruetruetrue || || || || truetruetruetrue", ( ", ( ", ( ", ( truetruetruetrue || || || || truetruetruetrue ) );) );) );) );
// // // // createcreatecreatecreate truthtruthtruthtruth table table table table forforforfor & (& (& (& (booleanbooleanbooleanboolean logicallogicallogicallogical AND) AND) AND) AND) operatoroperatoroperatoroperator
SystemSystemSystemSystem....outoutoutout....printfprintfprintfprintf( "%s( "%s( "%s( "%s\\\\n%s: %bn%s: %bn%s: %bn%s: %b\\\\n%s: %bn%s: %bn%s: %bn%s: %b\\\\n%s: %bn%s: %bn%s: %bn%s: %b\\\\n%s: %bn%s: %bn%s: %bn%s: %b\\\\nnnn\\\\n",n",n",n",
""""BooleanBooleanBooleanBoolean logicallogicallogicallogical AND (&)", "AND (&)", "AND (&)", "AND (&)", "falsefalsefalsefalse & & & & falsefalsefalsefalse", ( ", ( ", ( ", ( falsefalsefalsefalse & & & & falsefalsefalsefalse ),),),),
""""falsefalsefalsefalse & & & & truetruetruetrue", ( ", ( ", ( ", ( falsefalsefalsefalse & & & & truetruetruetrue ),),),),
""""truetruetruetrue & & & & falsefalsefalsefalse", ( ", ( ", ( ", ( truetruetruetrue & & & & falsefalsefalsefalse ),),),),
""""truetruetruetrue & & & & truetruetruetrue", ( ", ( ", ( ", ( truetruetruetrue & & & & truetruetruetrue ) );) );) );) );
Outline34
// // // // createcreatecreatecreate truthtruthtruthtruth table table table table forforforfor | (| (| (| (booleanbooleanbooleanboolean logicallogicallogicallogical inclusiveinclusiveinclusiveinclusive OR) OR) OR) OR) operatoroperatoroperatoroperator
SystemSystemSystemSystem....outoutoutout....printfprintfprintfprintf( "%s( "%s( "%s( "%s\\\\n%s: %bn%s: %bn%s: %bn%s: %b\\\\n%s: %bn%s: %bn%s: %bn%s: %b\\\\n%s: %bn%s: %bn%s: %bn%s: %b\\\\n%s: %bn%s: %bn%s: %bn%s: %b\\\\nnnn\\\\n",n",n",n",
""""BooleanBooleanBooleanBoolean logicallogicallogicallogical inclusiveinclusiveinclusiveinclusive OR (|)",OR (|)",OR (|)",OR (|)",
""""falsefalsefalsefalse | | | | falsefalsefalsefalse", ( ", ( ", ( ", ( falsefalsefalsefalse | | | | falsefalsefalsefalse ),),),),
""""falsefalsefalsefalse | | | | truetruetruetrue", ( ", ( ", ( ", ( falsefalsefalsefalse | | | | truetruetruetrue ),),),),
""""truetruetruetrue | | | | falsefalsefalsefalse", ( ", ( ", ( ", ( truetruetruetrue | | | | falsefalsefalsefalse ),),),),
""""truetruetruetrue | | | | truetruetruetrue", ( ", ( ", ( ", ( truetruetruetrue | | | | truetruetruetrue ) );) );) );) );
// // // // createcreatecreatecreate truthtruthtruthtruth table table table table forforforfor ^ (^ (^ (^ (booleanbooleanbooleanboolean logicallogicallogicallogical exclusiveexclusiveexclusiveexclusive OR) OR) OR) OR) operatoroperatoroperatoroperator
SystemSystemSystemSystem....outoutoutout....printfprintfprintfprintf( "%s( "%s( "%s( "%s\\\\n%s: %bn%s: %bn%s: %bn%s: %b\\\\n%s: %bn%s: %bn%s: %bn%s: %b\\\\n%s: %bn%s: %bn%s: %bn%s: %b\\\\n%s: %bn%s: %bn%s: %bn%s: %b\\\\nnnn\\\\n",n",n",n",
""""BooleanBooleanBooleanBoolean logicallogicallogicallogical exclusiveexclusiveexclusiveexclusive OR (^)", OR (^)", OR (^)", OR (^)",
""""falsefalsefalsefalse ^ ^ ^ ^ falsefalsefalsefalse", ( ", ( ", ( ", ( falsefalsefalsefalse ^ ^ ^ ^ falsefalsefalsefalse ),),),),
""""falsefalsefalsefalse ^ ^ ^ ^ truetruetruetrue", ( ", ( ", ( ", ( falsefalsefalsefalse ^ ^ ^ ^ truetruetruetrue ),),),),
""""truetruetruetrue ^ ^ ^ ^ falsefalsefalsefalse", ( ", ( ", ( ", ( truetruetruetrue ^ ^ ^ ^ falsefalsefalsefalse ),),),),
""""truetruetruetrue ^ ^ ^ ^ truetruetruetrue", ( ", ( ", ( ", ( truetruetruetrue ^ ^ ^ ^ truetruetruetrue ) );) );) );) );
// // // // createcreatecreatecreate truthtruthtruthtruth table table table table forforforfor ! (! (! (! (logicallogicallogicallogical negationnegationnegationnegation) ) ) ) operatoroperatoroperatoroperator
SystemSystemSystemSystem....outoutoutout....printfprintfprintfprintf( "%s( "%s( "%s( "%s\\\\n%s: %bn%s: %bn%s: %bn%s: %b\\\\n%s: %bn%s: %bn%s: %bn%s: %b\\\\n", "n", "n", "n", "LogicalLogicalLogicalLogical NOT (!)",NOT (!)",NOT (!)",NOT (!)",
"!"!"!"!falsefalsefalsefalse", ( !", ( !", ( !", ( !falsefalsefalsefalse ), "!), "!), "!), "!truetruetruetrue", ( !", ( !", ( !", ( !truetruetruetrue ) );) );) );) );
} // } // } // } // endendendend mainmainmainmain
} // } // } // } // endendendend classclassclassclass LogicalOperatorsLogicalOperatorsLogicalOperatorsLogicalOperators
Outline35
Conditional AND (&&)Conditional AND (&&)Conditional AND (&&)Conditional AND (&&)
false && false: falsefalse && false: falsefalse && false: falsefalse && false: false
false && true: falsefalse && true: falsefalse && true: falsefalse && true: false
true && false: falsetrue && false: falsetrue && false: falsetrue && false: false
true && true: truetrue && true: truetrue && true: truetrue && true: true
Conditional OR (||)Conditional OR (||)Conditional OR (||)Conditional OR (||)
false || false: falsefalse || false: falsefalse || false: falsefalse || false: false
false || true: truefalse || true: truefalse || true: truefalse || true: true
true || false: truetrue || false: truetrue || false: truetrue || false: true
true || true: truetrue || true: truetrue || true: truetrue || true: true
Boolean logical AND (&)Boolean logical AND (&)Boolean logical AND (&)Boolean logical AND (&)
false & false: falsefalse & false: falsefalse & false: falsefalse & false: false
false & true: falsefalse & true: falsefalse & true: falsefalse & true: false
true & false: falsetrue & false: falsetrue & false: falsetrue & false: false
t rue & true: truet rue & true: truet rue & true: truet rue & true: true
Boolean logical inclusive OR (|)Boolean logical inclusive OR (|)Boolean logical inclusive OR (|)Boolean logical inclusive OR (|)
false | false: falsefalse | false: falsefalse | false: falsefalse | false: false
false | true: truefalse | true: truefalse | true: truefalse | true: true
true | false: truetrue | false: truetrue | false: truetrue | false: true
true | true: truetrue | true: truetrue | true: truetrue | true: true
Outline36
Boolean logical exclusive OR (^)Boolean logical exclusive OR (^)Boolean logical exclusive OR (^)Boolean logical exclusive OR (^)
false ^ false: falsefalse ^ false: falsefalse ^ false: falsefalse ^ false: false
false ^ true: truefalse ^ true: truefalse ^ true: truefalse ^ true: true
true ^ false: truetrue ^ false: truetrue ^ false: truetrue ^ false: true
true ^ true: falsetrue ^ true: falsetrue ^ true: falsetrue ^ true: false
Logical NOT (!)Logical NOT (!)Logical NOT (!)Logical NOT (!)
!false: true!false: true!false: true!false: true
!true: false!true: false!true: false!true: false
37
4.16 Structured Programming Summary
• Sequence structure– “built-in” to Java
• Selection structure– if, if…else and switch
• Repetition structure– while, do…while and for
38
Fig. 4.21 Java’s single-entry/single-exit sequence, selection and repetition statements.
[t]
[f]
[f]
[t]
break
break
[t]break
[t]
[f][t]
[f]
[t]
[f]
[t]
[f]
Repetition
while statement do while statement for statement
SelectionSequence
if else statement (double selection)
if statement (single selection)
switch statement (multiple selection)
.
.
.
[t][f]
default
39
Rules for Forming Structured Programs 1) Begin with the “simplest activity diagram” (Fig. 5.23). 2) Any action state can be replaced by two action states in sequence. 3) Any action state can be replaced by any control statement (sequence,
if, if else, switch, while, do while or for). 4) Rules 2 and 3 can be applied as often as you like and in any order. Fig. 4.22 Rules for forming structured programs.
action state
Fig. 4.23 Simplest activity diagram.
40
Fig. 4.24 Repeatedly applying rule 2 of Fig. 4.22 to the simplest activity diagram.
.
.
.action state
action state
apply Rule 2
apply Rule 2
apply Rule 2
action state
action state
action state
action state
action state
action state
41
Fig. 4.25 Applying rule 3 of Fig. 4.22 to the simple st activity diagram.
action state
apply Rule 3
apply Rule 3
apply Rule 3 action stateaction state
action stateaction state action stateaction state
[f] [t]
[f] [t]
[f] [t][f] [t]
42
Fig. 4.26 Activity diagram with illegal syntax.
action state
action state
action state
action state