Options
while
do-while
for
Allow programs to control how many times a statement list is executed
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
99 trang |
Chia sẻ: candy98 | Lượt xem: 525 | Lượt tải: 0
Bạn đang xem trước 20 trang tài liệu Lecter Java: Program design - Chapter 6: Iteration, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
IterationCopyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.Java loopingOptionswhiledo-whileforAllow programs to control how many times a statement list is executedAveragingProblemExtract a list of positive numbers from standard input and produce their averageNumbers are one per lineA negative number acts as a sentinel to indicate that there are no more numbers to processObservationsCannot supply sufficient code using just assignments and conditional constructs to solve the problemDon’t how big of a list to processNeed ability to repeat code as neededAveragingProblemExtract a list of positive numbers from standard input and produce their averageNumbers are one per lineA negative number acts as a sentinel to indicate that there are no more numbers to processAlgorithmPrepare for processingGet first inputWhile there is an input to process do {Process current inputGet the next input}Perform final processingAveragingProblemExtract a list of positive numbers from standard input and produce their averageNumbers are one per lineA negative number acts as a sentinel to indicate that there are no more numbers to processSample runEnter positive numbers one per line.Indicate end of list with a negative number.4.50.51.3-1Average 2.1public class NumberAverage { // main(): application entry point public static void main(String[] args) throws IOException { // set up the list processing // 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 }}System.out.println("Enter positive numbers 1 per line.\n" + "Indicate end of the list with a negative number.");Scanner stdin = new Scanner(System.in);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");}While syntax and semanticsWhile semantics for averaging problemWhile SemanticsExecution Traceint 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");}Suppose input contains: 4.5 0.5 1.3 -1Execution Traceint 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");}Suppose input contains: 4.5 0.5 1.3 -10valuesProcessedExecution Traceint 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");}valueSumSuppose input contains: 4.5 0.5 1.3 -10valuesProcessed0Execution Traceint 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");}valueSumvalueSuppose input contains: 4.5 0.5 1.3 -10valuesProcessed04.5Execution Traceint 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");}valueSumvalueSuppose input contains: 4.5 0.5 1.3 -10valuesProcessed04.5Execution Traceint 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");}valueSumvalueSuppose input contains: 4.5 0.5 1.3 -10valuesProcessed04.54.5Execution Traceint 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");}valueSumvalueSuppose input contains: 4.5 0.5 1.3 -10valuesProcessed4.54.51Execution Traceint 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");}valueSumvalueSuppose input contains: 4.5 0.5 1.3 -11valuesProcessed4.54.50.5Execution Traceint 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");}valueSumvalueSuppose input contains: 4.5 0.5 1.3 -11valuesProcessed4.50.5Execution Traceint 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");}valueSumvalueSuppose input contains: 4.5 0.5 1.3 -11valuesProcessed4.50.55.0Execution Traceint 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");}valueSumvalueSuppose input contains: 4.5 0.5 1.3 -11valuesProcessed5.00.52Execution Traceint 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");}valueSumvalueSuppose input contains: 4.5 0.5 1.3 -12valuesProcessed5.00.51.3Execution Traceint 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");}valueSumvalueSuppose input contains: 4.5 0.5 1.3 -12valuesProcessed5.01.3Execution Traceint 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");}valueSumvalueSuppose input contains: 4.5 0.5 1.3 -12valuesProcessed5.01.36.3Execution Traceint 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");}valueSumvalueSuppose input contains: 4.5 0.5 1.3 -12valuesProcessed6.31.33Execution Traceint 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");}valueSumvalueSuppose input contains: 4.5 0.5 1.3 -13valuesProcessed6.31.3-1Execution Traceint 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");}valueSumvalueSuppose input contains: 4.5 0.5 1.3 -13valuesProcessed6.3-1Execution Traceint 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");}valueSumvalueSuppose input contains: 4.5 0.5 1.3 -13valuesProcessed6.3-1Execution Traceint 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");}valueSumvalueSuppose input contains: 4.5 0.5 1.3 -13valuesProcessed6.3-1average2.1Execution Traceint 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");}valueSumvalueSuppose input contains: 4.5 0.5 1.3 -13valuesProcessed6.3-1average2.1Converting text to strictly lowercasepublic static void main(String[] args) { Scanner stdin = new Scanner(System.in); System.out.println("Enter input to be converted:"); String converted = ""; while (stdin.hasNext()) { String currentLine = stdin.nextLine(); String currentConversion = currentLine.toLowerCase(); converted += (currentConversion + "\n"); } System.out.println("\nConversion is:\n" + converted);}Sample runProgram tracepublic static void main(String[] args) { Scanner stdin = new Scanner(System.in); System.out.println("Enter input to be converted:"); String converted = ""; while (stdin.hasNext()) { String currentLine = stdin.nextLine(); String currentConversion = currentLine.toLowerCase(); converted += (currentConversion + "\n"); } System.out.println("\nConversion is:\n" + converted);}Program tracepublic static void main(String[] args) { Scanner stdin = new Scanner(System.in); System.out.println("Enter input to be converted:"); String converted = ""; while (stdin.hasNext()) { String currentLine = stdin.nextLine(); String currentConversion = currentLine.toLowerCase(); converted += (currentConversion + "\n"); } System.out.println("\nConversion is:\n" + converted);}Program tracepublic static void main(String[] args) { Scanner stdin = new Scanner(System.in); System.out.println("Enter input to be converted:"); String converted = ""; while (stdin.hasNext()) { String currentLine = stdin.nextLine(); String currentConversion = currentLine.toLowerCase(); converted += (currentConversion + "\n"); } System.out.println("\nConversion is:\n" + converted);}Program tracepublic static void main(String[] args) { Scanner stdin = new Scanner(System.in); System.out.println("Enter input to be converted:"); String converted = ""; while (stdin.hasNext()) { String currentLine = stdin.nextLine(); String currentConversion = currentLine.toLowerCase(); converted += (currentConversion + "\n"); } System.out.println("\nConversion is:\n" + converted);}Program traceConverting text to strictly lowercasepublic static void main(String[] args) { Scanner stdin = new Scanner(System.in); System.out.println("Enter input to be converted:"); String converted = ""; while (stdin.hasNext()) { String currentLine = stdin.nextLine(); String currentConversion = currentLine.toLowerCase(); converted += (currentConversion + "\n"); } System.out.println("\nConversion is:\n" + converted);}Loop designQuestions to consider in loop design and analysisWhat initialization is necessary for the loop’s test expression?What initialization is necessary for the loop’s 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?Reading a fileBackgroundReading a fileClass FileProvides a system-independent way of representing a file nameConstructor File(String s)Creates a File with name sName can be either an absolute pathname or a pathname relative to the current working folderReading a fileScanner stdin = new Scanner(System.in);System.out.print("Filename: ");String filename = stdin.next();File file = new File(filename);Scanner fileIn = new Scanner(file);while (fileIn.hasNext()) { String currentLine = fileIn.nextLine(); System.out.println(currentLine);} fileIn.close();Reading a fileScanner stdin = new Scanner(System.in);System.out.print("Filename: ");String filename = stdin.next();File file = new File(filename);Scanner fileIn = new Scanner(file);while (fileIn.hasNext()) { String currentLine = fileIn.nextLine(); System.out.println(currentLine);} fileIn.close();Set up standard input streamReading a fileScanner stdin = new Scanner(System.in);System.out.print("Filename: ");String filename = stdin.next();File file = new File(filename);Scanner fileIn = new Scanner(file);while (fileIn.hasNext()) { String currentLine = fileIn.nextLine(); System.out.println(currentLine);} fileIn.close();Determine file nameReading a fileScanner stdin = new Scanner(System.in);System.out.print("Filename: ");String filename = stdin.next();File file = new File(filename);Scanner fileIn = new Scanner(file);while (fileIn.hasNext()) { String currentLine = fileIn.nextLine(); System.out.println(currentLine);} fileIn.close();Determine the associated fileReading a fileScanner stdin = new Scanner(System.in);System.out.print("Filename: ");String filename = stdin.next();File file = new File(filename);Scanner fileIn = new Scanner(file);while (fileIn.hasNext()) { String currentLine = fileIn.nextLine(); System.out.println(currentLine);} fileIn.close();Set up file streamReading a fileScanner stdin = new Scanner(System.in);System.out.print("Filename: ");String filename = stdin.next();File file = new File(filename);Scanner fileIn = new Scanner(file);while (fileIn.hasNext()) { String currentLine = fileIn.nextLine(); System.out.println(currentLine);} fileIn.close();Process lines one by oneReading a fileScanner stdin = new Scanner(System.in);System.out.print("Filename: ");String filename = stdin.next();File file = new File(filename);Scanner fileIn = new Scanner(file);while (fileIn.hasNext()) { String currentLine = fileIn.nextLine(); System.out.println(currentLine);} fileIn.close();Is there any textReading a fileScanner stdin = new Scanner(System.in);System.out.print("Filename: ");String filename = stdin.next();File file = new File(filename);Scanner fileIn = new Scanner(file);while (fileIn.hasNext()) { String currentLine = fileIn.nextLine(); System.out.println(currentLine);} fileIn.close();Get the next line of textReading a fileScanner stdin = new Scanner(System.in);System.out.print("Filename: ");String filename = stdin.next();File file = new File(filename);Scanner fileIn = new Scanner(file);while (fileIn.hasNext()) { String currentLine = fileIn.nextLine(); System.out.println(currentLine);} fileIn.close();Display current lineReading a fileScanner stdin = new Scanner(System.in);System.out.print("Filename: ");String filename = stdin.next();File file = new File(filename);Scanner fileIn = new Scanner(file);while (fileIn.hasNext()) { String currentLine = fileIn.nextLine(); System.out.println(currentLine);} fileIn.close();Make sure there is another to processIf not, loop is doneReading a fileScanner stdin = new Scanner(System.in);System.out.print("Filename: ");String filename = stdin.next();File file = new File(filename);Scanner fileIn = new Scanner(file);while (fileIn.hasNext()) { String currentLine = fileIn.nextLine(); System.out.println(currentLine);} fileIn.close();Close the streamThe For StatementThe For StatementThe For StatementThe For StatementThe For StatementFor statement syntaxExecution Tracefor (int i = 0; i maximumValue) { maximumValue = x; } } Facilitator load() public void load(String s) throws IOException { // get a reader for the file Scanner fileIn = new Scanner( new File(s) ); // add values one by one while (fileIn.hasNext()) { double x = fileIn.nextDouble); addValue(x); } // close up file fileIn.close(); }