20 likes | 136 Views
6-1 While Loops (Pre –Test) while ( boolean condition is true) //enter loop Count Controlled: count = 0; // Initialize Loop Control Variable (LCV) – Prime loop! while( count < = 10 ) // Enter the loop if LCV check is true { System.out.println (count);
E N D
6-1 While Loops (Pre –Test) • while ( boolean condition is true) //enter loop • Count Controlled: count = 0; // Initialize Loop Control Variable (LCV) – Prime loop! while( count < = 10 ) // Enter the loop if LCV check is true { System.out.println(count); count++; // Update LCV – Be careful where you put this! } • Event Controlled : Consider the following & assume a getNum( ) method exists for input: String input; double sum = 0; int num, count =0; num = getNum( ); // Priming read! while ( num != -999 ) // -999 is called a sentinel value (6.4 p247) { count++; sum + = num; num = getNum( ); } System.out.print(“A sum of “ +sum +”,with a count of “ +count +” results in…”);
do – while loop (Post –Test) import javax.swing.JOptionPane; class void Average( ) { //================================================================== public static intgetNum( ) { String input; do //do-while a post-test loop. Why? { input = JOptionPane.showInput Dialog(“Enter number <-999 terminates>”); }while( input = = null || input = =“”); return Integer.parseInt(input); } //================================================================== public static void main( ) { double sum = 0; int num, ave, count =0; num = getNum( ); while ( num != -999 ) { count++; sum + = num; num = getNum( ); } ave = (int)Math.round( sum/ ct ); System.out.print(“ Average of “ +count +” values with a sum of ” +sum +” is “+ave); } }