D06 PROGRAMMING with JAVA



Similar documents
Iteration CHAPTER 6. Topic Summary

LOOPS CHAPTER CHAPTER GOALS

D06 PROGRAMMING with JAVA

D06 PROGRAMMING with JAVA

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Sample CSE8A midterm Multiple Choice (circle one)

D06 PROGRAMMING with JAVA

AP Computer Science Java Mr. Clausen Program 9A, 9B

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

D06 PROGRAMMING with JAVA

This loop prints out the numbers from 1 through 10 on separate lines. How does it work? Output:

D06 PROGRAMMING with JAVA. Ch3 Implementing Classes

Introduction to Java

AP Computer Science Static Methods, Strings, User Input

Object Oriented Software Design

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

J a v a Quiz (Unit 3, Test 0 Practice)

Unit 6. Loop statements

Topic 11 Scanner object, conditional execution

D06 PROGRAMMING with JAVA

Arrays. Introduction. Chapter 7

Chapter 2 Introduction to Java programming

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

In this Chapter you ll learn:

IRA EXAMPLES. This topic has two examples showing the calculation of the future value an IRA (Individual Retirement Account).

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

5.2 Q2 The control variable of a counter-controlled loop should be declared as: a.int. b.float. c.double. d.any of the above. ANS: a. int.

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Object Oriented Software Design

D06 PROGRAMMING with JAVA

Using Two-Dimensional Arrays

6. Control Structures

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

Building Java Programs

JavaScript: Control Statements I

Building Java Programs

Example of a Java program

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Building Java Programs

Chapter 2: Elements of Java

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall

Part I. Multiple Choice Questions (2 points each):

While Loop. 6. Iteration

Using Files as Input/Output in Java 5.0 Applications

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

Arrays in Java. Working with Arrays

AP Computer Science Java Subset

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Statements and Control Flow

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

CS170 Lab 11 Abstract Data Types & Objects

Moving from CS 61A Scheme to CS 61B Java

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Two-way selection. Branching and Looping

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

Visual Logic Instructions and Assignments

MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION

Contents. 9-1 Copyright (c) N. Afshartous

Object-Oriented Programming in Java

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Statements and Control Flow

Computer Programming I

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Introduction to Java. CS 3: Computer Programming in Java

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Homework/Program #5 Solutions

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Building Java Programs

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

Some Scanner Class Methods

Basics of Java Programming Input and the Scanner class

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

Java Basics: Data Types, Variables, and Loops

Chapter 20 Streams and Binary Input/Output. Big Java Early Objects by Cay Horstmann Copyright 2014 by John Wiley & Sons. All rights reserved.

Chapter 3. Input and output. 3.1 The System class

JAVA ARRAY EXAMPLE PDF

UEE1302 (1102) F10 Introduction to Computers and Programming

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement

13 File Output and Input

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

While and Do-While Loops Summer 2010 Margaret Reid-Miller

Chapter 2 Elementary Programming

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Install Java Development Kit (JDK) 1.8

1.3 Conditionals and Loops

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Two-Dimensional Arrays. Multi-dimensional Arrays. Two-Dimensional Array Indexing

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

Explain the relationship between a class and an object. Which is general and which is specific?

Perl in a nutshell. First CGI Script and Perl. Creating a Link to a Script. print Function. Parsing Data 4/27/2009. First CGI Script and Perl

Introduction to Java Lecture Notes. Ryan Dougherty

Scanner sc = new Scanner(System.in); // scanner for the keyboard. Scanner sc = new Scanner(System.in); // scanner for the keyboard

The C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures

6.1. Example: A Tip Calculator 6-1

I PUC - Computer Science. Practical s Syllabus. Contents

Transcription:

Cicles Formatius de Grau Superior Desenvolupament d Aplicacions Informàtiques D06 PROGRAMMING with JAVA Ch7 Iteration PowerPoint presentation, created by Angel A. Juan - ajuanp(@)gmail.com, for accompanying the book Big Java, by Cay S. Horstmann (2006)

Chapter Goals To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To understand nested loops To learn how to process input To implement simulations

while Loops The while statement executes a statement or a block statement repeatedly while the condition is true: while (condition) { } statements; Example (calculating the growth of an investment): Invest $10,000, 5% interest, compounded annually Year Balance 0 $10,000 1 $10,500 2 $11,025 3 $11,576.25 4 $12,155.06 5 $12,762.82 When When has has the the bank bank account account reached reached a a particular particular balance? balance? while (balance < targetbalance) { year++; double interest = balance * rate / 100; balance = balance + interest; }

File Investment.java 01: /** 02: A class to monitor the growth of an investment that 03: accumulates interest at a fixed annual rate. 04: */ 05: public class Investment 06: { 07: /** 08: Constructs an Investment object from a starting balance 09: and interest rate. 10: @param abalance the starting balance 11: @param arate the interest rate in percent 12: */ 13: public Investment(double abalance, double arate) 14: { 15: balance = abalance; 16: rate = arate; 17: years = 0; 18: } 19: Continued

File Investment.java 20: /** 21: Keeps accumulating interest until a target balance has 22: been reached. 23: @param targetbalance the desired balance 24: */ 25: public void waitforbalance(double targetbalance) 26: { 27: while (balance < targetbalance) 28: { 29: years++; 30: double interest = balance * rate / 100; 31: balance = balance + interest; 32: } 33: } 34: 35: /** 36: Gets the current investment balance. 37: @return the current balance 38: */ Continued

File Investment.java 39: public double getbalance() 40: { 41: return balance; 42: } 43: 44: /** 45: Gets the number of years this investment has 46: accumulated interest. 47: @return the number of years since the start of the investment 48: */ 49: public int getyears() 50: { 51: return years; 52: } 53: 54: private double balance; 55: private double rate; 56: private int years; 57: }

File InvestmentTester.java 01: /** 02: This program computes how long it takes for an investment 03: to double. 04: */ 05: public class InvestmentTester 06: { 07: public static void main(string[] args) 08: { 09: final double INITIAL_BALANCE = 10000; 10: final double RATE = 5; 11: Investment invest = new Investment(INITIAL_BALANCE, RATE); 12: invest.waitforbalance(2 * INITIAL_BALANCE); 13: int years = invest.getyears(); 14: System.out.println("The investment doubled after " 15: + years + " years"); 16: } 17: } Output The investment doubled after 15 years

while Loop Flowchart The while statement is often called a loop. If you draw a flowchart, you will see that the control loops backwards to the test after every iteration Figure 1: Flowchart of a while Loop The following is an infinite loop. It executes the statement block over and over, without terminating: while (true) { } statements;

Syntax 7.1: The while Statement while (condition) statement Example: while (balance < targetbalance) { year++; double interest = balance * rate / 100; balance = balance + interest; } Purpose: To repeatedly execute a statement as long as a condition is true

Self Check 1. How often is the statement in the loop while (false) statement; executed? 2. What would happen if RATE was set to 0 in the main method of the InvestmentTester program?

Answers 1. Never 2. The waitforbalance method would never return due to an infinite loop

Common Error: Infinite Loops An infinite loop is a loop that runs forever and can be stopped only by killing the program or restarting the computer A common reason for infinite loops is forgetting to advance the variable that controls the loop: int years = 0; while (years < 20) { double interest = balance * rate / 100; balance = balance + interest; } Another common reason for an infinite loop is accidentally incrementing a counter that should be decremented: int years = 20; while (years > 0) { years++; // Oops, should have been years-- double interest = balance * rate / 100; balance = balance + interest; }

Common Error: Off-By-One Errors Consider the computation of the number of years that are required to double an investment: int years = 0; while (balance < 2 * initialbalance) { years++; double interest = balance * rate / 100; balance = balance + interest; } System.out.println("The investment reached the target after " + years + " years."); Should years start at 0 or 1? Should the test be < or <=? Off-by-one errors are easy to avoid, simply by thinking through a couple of test cases and using the information from the test cases to come up with a rationale for the correct loop condition

do Loops Sometimes you want to execute the body of a loop at least once and perform the loop test after the body was executed. The do loop serves that purpose: do statement while (condition); The statement is executed while the condition is true. The condition is tested after the statement is executed, so the statement is executed at least once: double value; do { System.out.print("Please enter a positive number: "); value = in.nextdouble(); } while (value <= 0); Continued

do Loops Figure 2: Flowchart of a do Loop You can always replace a do loop with a while loop, by introducing a Boolean control variable: boolean done = false; while (!done) { System.out.print("Please enter a positive number: "); value = in.nextdouble(); if (value > 0) done = true; }

Spaghetti Code Because the lines denoting goto statements weave back and forth in complex flowcharts, the resulting code is named spaghetti code Figure 3: Spaghetti Code

for Loops One of the most common loop types has the form: i = start; while (i <= end) {... i++; } Because this loop is so common, there is a special form for it, the for loop: for (i = start; i <= end; i++) {... } You can also declare the loop counter variable inside the loop header. That convenient shorthand restricts the use of the variable to the body of the loop for (int i = start; i <= end; i++) {... } Continued

for Loops Examples: for (int i = 1; i <= n; i++) { double interest = balance * rate / 100; balance = balance + interest; } for (years = n; years > 0; years--)... for (x = -10; x <= 10; x = x + 0.5)... Figure 4: Flowchart of a for Loop

Syntax 7.2: The for Statement for (initialization; condition; update) statement Example: for (int i = 1; i <= n; i++) { double interest = balance * rate / 100; balance = balance + interest; } Purpose: To execute an initialization, then keep executing a statement and updating an expression while a condition is true

File Investment.java 01: /** 02: A class to monitor the growth of an investment that 03: accumulates interest at a fixed annual rate 04: */ 05: public class Investment 06: { 07: /** 08: Constructs an Investment object from a starting 09: balance and interest rate. 10: @param abalance the starting balance 11: @param arate the interest rate in percent 12: */ 13: public Investment(double abalance, double arate) 14: { 15: balance = abalance; 16: rate = arate; 17: years = 0; 18: } Continued

File Investment.java 19: 20: /** 21: Keeps accumulating interest until a target balance 22: has been reached. 23: @param targetbalance the desired balance 24: */ 25: public void waitforbalance(double targetbalance) 26: { 27: while (balance < targetbalance) 28: { 29: years++; 30: double interest = balance * rate / 100; 31: balance = balance + interest; 32: } 33: } 34: Continued

File Investment.java 35: /** 36: Keeps accumulating interest for a given number of years. 37: @param n the number of years 38: */ 39: public void waityears(int n) 40: { 41: for (int i = 1; i <= n; i++) 42: { 43: double interest = balance * rate / 100; 44: balance = balance + interest; 45: } 46: years = years + n; 47: } 48: 49: /** 50: Gets the current investment balance. 51: @return the current balance 52: */ Continued

File Investment.java 53: public double getbalance() 54: { 55: return balance; 56: } 57: 58: /** 59: Gets the number of years this investment has 60: accumulated interest. 61: @return the number of years since the start of the investment 62: */ 63: public int getyears() 64: { 65: return years; 66: } 67: Continued

File Investment.java 68: private double balance; 69: private double rate; 70: private int years; 71: }

File InvestmentTester.java 01: /** 02: This program computes how much an investment grows in 03: a given number of years. 04: */ 05: public class InvestmentTester 06: { 07: public static void main(string[] args) 08: { 09: final double INITIAL_BALANCE = 10000; 10: final double RATE = 5; 11: final int YEARS = 20; 12: Investment invest = new Investment(INITIAL_BALANCE, RATE); 13: invest.waityears(years); 14: double balance = invest.getbalance(); 15: System.out.printf("The balance after %d years is %.2f\n", 16: YEARS, balance); 17: } 18: } Output The balance after 20 years is 26532.98

Self Check 3. Rewrite the for loop in the waityears method as a while loop 4. How many times does the following for loop execute? for (i = 0; i <= 10; i++) System.out.println(i * i);

Answers 3. int i = 1; while (i <= n) { double interest = balance * rate / 100; balance = balance + interest; i++; } 4. 11 times

Common Errors: Semicolons A semicolon that shouldn't be there: sum = 0; for (i = 1; i <= 10; i++); sum = sum + i; System.out.println(sum); Occasionally all the work of a loop is already done in the loop header. If you do run into a loop without a body, it is important that you make sure the semicolon is not forgotten for (years = 1; (balance = balance + balance * rate / 100) < targetbalance; years++) System.out.println(years); You can avoid this error by using an empty block {} instead of an empty statement

Scope of variables in a for loop It is legal in Java to declare a variable in the header of a for loop: for (int i = 1; i <= n; i++) {... } // i no longer defined here The scope of the variable extends to the end of the for loop. Therefore, i is no longer defined after the loop ends In the loop header, you can declare multiple variables, as long as they are of the same type and you can include multiple update expressions, separated by commas. Better than that, make the for loop control a single counter, and update the other variable explicitly for (int i = 0, j = 10; i <= 10; i++, j--) {... } int j = 10; for (int i = 0; i <= 10; i++) {... } j--;

Nested Loops Sometimes, the body of a loop is again a loop. We say that the inner loop is nested inside an outer loop. This happens often when you process two-dimensional structures, such as tables Example: create triangle pattern (loop through rows) [] [][] [][][] [][][][] for (int i = 1; i <= n; i++) { // make triangle row } for (int j = 1; j <= i; j++) r = r + "[]"; r = r + "\n";

File Triangle.java 01: /** 02: This class describes triangle objects that can be 03: displayed as shapes like this: 04: [] 05: [][] 06: [][][] 07: */ 08: public class Triangle 09: { 10: /** 11: Constructs a triangle. 12: @param awidth the number of [] in the last row of the triangle. 13: */ 14: public Triangle(int awidth) 15: { 16: width = awidth; 17: } 18: Continued

File Triangle.java 19: /** 20: Computes a string representing the triangle. 21: @return a string consisting of [] and newline characters 22: */ 23: public String tostring() 24: { 25: String r = ""; 26: for (int i = 1; i <= width; i++) 27: { 28: // Make triangle row 29: for (int j = 1; j <= i; j++) 30: r = r + "[]"; 31: r = r + "\n"; 32: } 33: return r; 34: } 35: 36: private int width; 37: }

File TriangleTester.java 01: /** 02: This program tests the Triangle class. 03: */ 04: public class TriangleTester 05: { 06: public static void main(string[] args) 07: { 08: Triangle small = new Triangle(3); 09: System.out.println(small.toString()); 10: 11: Triangle large = new Triangle(15); 12: System.out.println(large.toString()); 13: } 14: }

Self Check 5. How would you modify the nested loops so that you print a square instead of a triangle? 6. What is the value of n after the following nested loops? int n = 0; for (int i = 1; i <= 5; i++) for (int j = 0; j < i; j++) n = n + j;

Answers 5. Change the inner loop to for (int j = 1; j <= width; j++) 6. 20

Processing Sentinel Values One common method for indicating the end of a data set is a sentinel value, a value that is not part of the data. Instead, the sentinel value indicates that the data has come to and end Some programmers choose numbers such as 0 or -1 as sentinel values. A better idea is to use an input that is not a number, such as the letter Q Of course, we need to read each input as a string, not a number. Once we have tested that the input is not the letter Q, we convert the string into a number: System.out.print("Enter value, Q to quit: "); String input = in.next(); if (input.equalsignorecase("q")) We are done else { double x = Double.parseDouble(input);... }

Symmetric and Asymmetric Bounds It is easy to write a symmetric loop with i going from 1 to n: for (i = 1; i <= n; i++) But, when traversing the characters in a string, the bounds are asymmetric for (i = 0; i < str.length(); i++) The values for i are bounded by 0<=i<str.length(), with a <= comparison to the left and a < comparison to the right It is not a good idea to force symmetry artificially: for (i = 0; i <= str.length() - 1; i++)

Loop and a half Sometimes termination condition of a loop can only be evaluated in the middle of the loop Then, introduce a boolean variable to control the loop: boolean done = false; while (!done) { Print prompt String input = read input; if (end of input indicated) done = true; else { // Process input } }

The break and continue statements In addition to breaking out of a switch statement, a break statement can also be used to exit a while, for, or do loop In Java, there is a second form of the break statement that is used to break out of a nested statement. The statement break label; immediately jumps to the end of the statement that is tagged with a label Finally, there is another goto-like statement, the continue statement, which jumps to the end of the current iteration of the loop while (!done) { String input = in.next(); } if (input.equalsignorecase("q")) { done = true; continue; // Jump to the end of the loop body } double x = Double.parseDouble(input); data.add(x); // continue statement jumps here

File InputTester.java 01: import java.util.scanner; 02: 03: /** 04: This program computes the average and maximum of a set 05: of input values. 06: */ 07: public class InputTester 08: { 09: public static void main(string[] args) 10: { 11: Scanner in = new Scanner(System.in); 12: DataSet data = new DataSet(); 13: 14: boolean done = false; 15: while (!done) 16: { Continued

File InputTester.java 17: System.out.print("Enter value, Q to quit: "); 18: String input = in.next(); 19: if (input.equalsignorecase("q")) 20: done = true; 21: else 22: { 23: double x = Double.parseDouble(input); 24: data.add(x); 25: } 26: } 27: 28: System.out.println("Average = " + data.getaverage()); 29: System.out.println("Maximum = " + data.getmaximum()); 30: } 31: }

File DataSet.java 01: /** 02: Computes the average of a set of data values. 03: */ 04: public class DataSet 05: { 06: /** 07: Constructs an empty data set. 08: */ 09: public DataSet() 10: { 11: sum = 0; 12: count = 0; 13: maximum = 0; 14: } 15: 16: /** 17: Adds a data value to the data set 18: @param x a data value 19: */ Continued

File DataSet.java 20: public void add(double x) 21: { 22: sum = sum + x; 23: if (count == 0 maximum < x) maximum = x; 24: count++; 25: } 26: 27: /** 28: Gets the average of the added data. 29: @return the average or 0 if no data has been added 30: */ 31: public double getaverage() 32: { 33: if (count == 0) return 0; 34: else return sum / count; 35: } 36: Continued

File DataSet.java 37: /** 38: Gets the largest of the added data. 39: @return the maximum or 0 if no data has been added 40: */ 41: public double getmaximum() 42: { 43: return maximum; 44: } 45: 46: private double sum; 47: private double maximum; 48: private int count; 49: } Enter value, Q to quit: 10 Enter value, Q to quit: 0 Enter value, Q to quit: -1 Enter value, Q to quit: Q Average = 3.0 Output Maximum = 10.0

Self Check 7. Why does the InputTester class call in.next and not in.nextdouble? 8. Would the DataSet class still compute the correct maximum if you simplified the update of the maximum field in the add method to the following statement? if (maximum < x) maximum = x;

Answers 7. Because we don't know whether the next input is a number or the letter Q. 8. No. If all input values are negative, the maximum is also negative. However, the maximum field is initialized with 0. With this simplification, the maximum would be falsely computed as 0.

Random Numbers and Simulations In a simulation, you generate random events and evaluate their outcomes The Random class of the Java library implements a random number generator, which produces numbers that appear to be completely random. To generate random numbers, you construct an object of the Random class, and then apply one of the following methods, nextint(n) or nextdouble(): Random generator = new Random(); int n = generator.nextint(a); // 0 <= n < a double x = generator.nextdouble(); // 0 <= x < 1 Example: throw die (random number between 1 and 6) int d = 1 + generator.nextint(6);

File Die.java 01: import java.util.random; 02: 03: /** 04: This class models a die that, when cast, lands on a 05: random face. 06: */ 07: public class Die 08: { 09: /** 10: Constructs a die with a given number of sides. 11: @param s the number of sides, e.g. 6 for a normal die 12: */ 13: public Die(int s) 14: { 15: sides = s; 16: generator = new Random(); 17: } 18: Continued

File Die.java 19: /** 20: Simulates a throw of the die 21: @return the face of the die 22: */ 23: public int cast() 24: { 25: return 1 + generator.nextint(sides); 26: } 27: 28: private Random generator; 29: private int sides; 30: }

File DieTester.java 01: /** 02: This program simulates casting a die ten times. 03: */ 04: public class DieTester 05: { 06: public static void main(string[] args) 07: { 08: Die d = new Die(6); 09: final int TRIES = 10; 10: for (int i = 1; i <= TRIES; i++) 11: { 12: int n = d.cast(); 13: System.out.print(n + " "); 14: } 15: System.out.println(); 16: } 6 5 6 3 2 6 3 4 4 1 17: } Output Second Run 3 2 2 1 6 5 3 4 1 2

Self Check 9. How do you use a random number generator to simulate the toss of a coin?

Answers 9. int n = generator.nextint(2); // 0 = heads, 1 = tails

Chapter Summary A while statement executes a block of code repeatedly. A condition controls how often the loop is executed An off-by-one error is a common error when programming loops. Think through simple test cases to avoid this type of error You use a for loop when a variable runs from a starting to an ending value with a constant increment or decrement Loops can be nested. A typical example of nested loops is printing a table with rows and columns Sometimes, the termination condition of a loop can only be evaluated in the middle of a loop. You can introduce a sentinel (Boolean) variable to control such a loop Make a choice between symmetric and asymmetric loop bonds Count the number of iterations to check that you for loop is correct In a simulation, you repeatedly generate random numbers and use them to simulate an activity