1 Iteration. 2 Java looping Options while do-while for Allow programs to control how many times a statement list is executed

Embed Size (px)

DESCRIPTION

3 Averaging  Problem Extract a list of positive numbers from standard input and produce their average  Numbers are one per line  A negative number acts as a sentinel to indicate that there are no more numbers to process  Observations Cannot supply sufficient code using just assignments and conditional constructs to solve the problem  Don’t how big of a list to process Need ability to repeat code as needed

Citation preview

1 Iteration 2 Java looping Options while do-while for Allow programs to control how many times a statement list is executed 3 Averaging Problem Extract a list of positive numbers from standard input and produce their average Numbers are one per line A negative number acts as a sentinel to indicate that there are no more numbers to process Observations Cannot supply sufficient code using just assignments and conditional constructs to solve the problem Dont how big of a list to process Need ability to repeat code as needed 4 Averaging Algorithm Prepare for processing Get first input While there is an input to process do { Process current input Get the next input } Perform final processing 5 Averaging Problem Extract a list of positive numbers from standard input and produce their average Numbers are one per line A negative number acts as a sentinel to indicate that there are no more numbers to process Sample run Enter positive numbers one per line. Indicate end of list with a negative number Average 2.1 public class NumberAverage { // main(): application entry point public static void main(String[] args) { // set up the input // prompt user for values // get first value // process values one-by-one while (value >= 0) { // add value to running total // processed another value // prepare next iteration - get next value } // display result if (valuesProcessed > 0) // compute and display average else // indicate no average to display } int valuesProcessed = 0; double valueSum = 0; // set up the input Scanner stdin = new Scanner (System.in); // prompt user for values System.out.println("Enter positive numbers 1 per line.\n" + "Indicate end of the list with a negative number."); // get first value double value = stdin.nextDouble(); // process values one-by-one while (value >= 0) { valueSum += value; ++valuesProcessed; value = stdin.nextDouble(); } // display result if (valuesProcessed > 0) { double average = valueSum / valuesProcessed; System.out.println("Average: " + average); } else { System.out.println("No list to average"); } 8 While syntax and semantics Logical expression that determines whether Action is to be executed while ( Expression ) Action Action is either a single statement or a statement list within braces 9 While semantics for averaging problem // process values one-by-one while ( value >= 0 ) { // add value to running total valueSum += value; // we processed another value ++valueProcessed; // prepare to iterate get the next input value = stdin.nextDouble(); } Test expression is evaluated at the start of each iteration of the loop. If test expression is true, these statements are executed. Afterward, the test expression is reevaluated and the process repeats 10 While Semantics Expression Action true false Expression is evaluated at the start of each iteration of the loop If Expression is true, Action is executed If Expression is false, program execution continues with next statement 11 int valuesProcessed = 0; double valueSum = 0; double value = stdin.nextDouble(); while (value >= 0) { valueSum += value; ++valuesProcessed; value = stdin.nextDouble(); } if (valuesProcessed > 0) { double average = valueSum / valuesProcessed; System.out.println("Average: " + average); } else { System.out.println("No list to average"); } int valuesProcessed = 0; double valueSum = 0; double value = stdin.nextDouble(); while (value >= 0) { valueSum += value; ++valuesProcessed; value = stdin.nextDouble(); if (valuesProcessed > 0) { double average = valueSum / valuesProcessed; System.out.println("Average: " + average); Execution Trace Suppose input contains: valuesProcessed valueSum 0 value 4.5 Suppose input contains: Suppose input contains: Suppose input contains: Suppose input contains: average 2.1 12 Converting text to strictly lowercase public static void main(String[] args) { Scanner stdin = new Scanner (System.in); System.out.println("Enter input to be converted:"); String converted = ""; String currentLine = stdin.nextLine(); while (currentLine != null) { String currentConversion = currentLine.toLowerCase(); converted += (currentConversion + "\n"); currentLine = stdin.nextLine(); } System.out.println("\nConversion is:\n" + converted); } 13 Sample run A Ctrl+z was entered. It is the Windows escape sequence for indicating end-of-file An empty line was entered 14 Program trace public static void main(String[] args) { Scanner stdin = new Scanner (System.in); System.out.println("Enter input to be converted:"); String converted = ""; String currentLine = stdin.nextLine(); while (currentLine != null) { String currentConversion = currentLine.toLowerCase(); converted += (currentConversion + "\n"); currentLine = stdin.nextLine(); } System.out.println("\nConversion is:\n" + converted); } public static void main(String[] args) { Scanner stdin = new Scanner (System.in); System.out.println("Enter input to be converted:"); String converted = ""; String currentLine = stdin.nextLine(); while (currentLine != null) { String currentConversion = currentLine.toLowerCase(); converted += (currentConversion + "\n"); currentLine = stdin.nextLine(); } System.out.println("\nConversion is:\n" + converted); } 15 Program trace Representation of lower case conversion of current input line converted += (currentConversion + "\n"); The append assignment operator updates the representation of converted to include the current input line Newline character is needed because method nextLine() "strips" them from the input 16 Converting text to strictly lowercase public static void main(String[] args) { Scanner stdin = new Scanner (System.in); System.out.println("Enter input to be converted:"); String converted = ""; String currentLine = stdin.nextLine(); while (currentLine != null) { String currentConversion = currentLine.toLowerCase(); converted += (currentConversion + "\n"); currentLine = stdin.nextLine(); } System.out.println("\nConversion is:\n" + converted); } 17 Loop design Questions to consider in loop design and analysis What initialization is necessary for the loops test expression? What initialization is necessary for the loops processing? What causes the loop to terminate? What actions should the loop perform? What actions are necessary to prepare for the next iteration of the loop? What conditions are true and what conditions are false when the loop is terminated? When the loop completes what actions are need to prepare for subsequent program processing? 18 Reading a file Background Same Scanner class! Scanner fileIn = new Scanner (new File (filename) ); The File class allows access to files Its in the java.io package filename is a String 19 Reading a file Class File Allows access to files (etc.) on a hard drive Constructor File (String s) Opens the file with name s so that values can be extracted Name can be either an absolute pathname or a pathname relative to the current working folder 20 Reading a file Scanner stdin = new Scanner (System.in); System.out.print("Filename: "); String filename = stdin.nextLine(); Scanner fileIn = new Scanner (new File (filename)); String currentLine = fileIn.nextLine(); while (currentLine != null) { System.out.println(currentLine); currentLine = fileIn.nextLine(); } Scanner stdin = new Scanner (System.in); System.out.print("Filename: "); String filename = stdin.nextLine(); Scanner fileIn = new Scanner (new File (filename)); String currentLine = fileIn.nextLine(); while (currentLine != null) { System.out.println(currentLine); currentLine = fileIn.nextLine(); } Set up standard input streamDetermine file nameSet up file streamProcess lines one by oneGet first lineMake sure got a line to processDisplay current lineGet next lineMake sure got a line to process If not, loop is done Close the file stream 21 Quick survey I feel I understand while loops I feel I understand while loops a) Very well b) With some review, Ill be good c) Not really d) Not at all 22 Star Wars: Episode III trailer No, really! No, really! 23 End of lecture on 16 March 2005 At this point, we moved back to the chapter 5 slides, and did slides 24 The For Statement currentTerm = 1; for ( int i = 0; i < 5; ++i ) { System.out.println(currentTerm); currentTerm *= 2; } After each iteration of the body of the loop, the update expression is reevaluated The body of the loop iterates while the test expression is true int Initialization step is performed only once -- just prior to the first evaluation of the test expression The body of the loop displays the current term in the number series. It then determines what is to be the new current number in the series ForExpr Action truefalse ForInit PostExpr Evaluated once at the beginning of the for statements's execution The ForExpr is evaluated at the start of each iteration of the loop If ForExpr is true, Action is executed After the Action has completed, the PostExpression is evaluated If ForExpr is false, program execution continues with next statement After evaluating the PostExpression, the next iteration of the loop starts 26 for statement syntax Logical test expression that determines whether the action and update step are executed for ( ForInit ; ForExpression ; ForUpdate ) Action Update step is performed after the execution of the loop body Initialization step prepares for the first evaluation of the test expression The body of the loop iterates whenever the test expression evaluates to true 27 for vs. while A for statement is almost like a while statement for ( ForInit; ForExpression; ForUpdate ) Action is ALMOST the same as: ForInit; while ( ForExpression ) { Action; ForUpdate; } This is not an absolute equivalence! Well see when they are different below 28 Variable declaration You can declare a variable in any block: while ( true ) { int n = 0; n++; System.out.println (n); } System.out.println (n); Variable n gets created (and initialized) each time Thus, println() always prints out 1 Variable n is not defined once while loop ends As n is not defined here, this causes an error 29 Variable declaration You can declare a variable in any block: if ( true ) { int n = 0; n++; System.out.println (n); } System.out.println (n); Only difference from last slide 30 System.out.println("i is " + i); } System.out.println("all done"); System.out.println("i is " + i); } System.out.println("all done"); i is 0 i is 1 i is 2 all done Execution Trace i 0 int i = 0;i < 3;++ifor () {int i = 0;i < 3;++i 123 Variable i has gone out of scope it is local to the loop 31 for vs. while An example when a for loop can be directly translated into a while loop: int count; for ( count = 0; count < 10; count++ ) { System.out.println (count); } Translates to: int count; count = 0; while (count < 10) { System.out.println (count); count++; } 32 for vs. while An example when a for loop CANNOT be directly translated into a while loop: for ( int count = 0; count < 10; count++ ) { System.out.println (count); } Would (mostly) translate as: int count = 0; while (count < 10) { System.out.println (count); count++; } count IS defined here count is NOT defined here only difference 33 for loop indexing Java (and C and C++) indexes everything from zero Thus, a for loop like this: for ( int i = 0; i < 10; i++ ) {... } Will perform the action with i being value 0 through 9, but not 10 To do a for loop from 1 to 10, it would look like this: for ( int i = 1; i