Anda di halaman 1dari 42

Loops (cont.

Loop Statements
while statement
while ( condition ) statement;

do {

do statement

statement list; } while ( condition );

for ( initialization ; condition ; increment ) statement;

for statement

Flowchart of a while Loop


while ( condition ) statement;
condition evaluated true statement false

Example
System.out.print( Enter a month (1 to 12): ); int month = scan.nextInt(); while (month < 1 || month > 12) { System.out.println( month + is not a valid month. ); System.out.print( Enter a month (1 to 12): ); month = scan.nextInt(); } // set initial value of month so that the while condition // below is false initially int month = -1; while (month < 1 || month > 12) { System.out.print( Enter a month (1 to 12): ); month = scan.nextInt(); }

The do Statement: Syntax


Both do and while are reserved words
do { statement; } while ( condition );

The statement is executed once initially, then the condition is evaluated The statement is repetitively executed until the condition becomes false

Flowchart of a do Loop
do { statement; } while ( condition );
statement true condition evaluated false

Comparing the while and do Loops


while loop do loop

condition evaluated true true statement false

statement

condition evaluated false

A do loop is similar to a while loop, except that the condition is evaluated

after the body of the loop is executed Therefore the body of a do loop will execute at least once

Example

int month; // no need to initialize month do {

System.out.print( Enter a month (1 to 12): );


month = scan.nextInt(); } while (month < 1 || month > 12);

// beginning of the next statement

The for Statement: Syntax


Reserved word

The initialization portion is executed once before the loop begins

The statement is executed until the condition becomes false

for ( initialization ; condition ; increment ) statement;

Both semi-colons are always required The increment portion is executed at the end of each iteration

The for Statement: Syntax


Each expression in the header of a for loop is optional
if the initialization is left out, no initialization is performed if the condition is left out, it is always considered to be true if the increment is left out, no increment operation is performed

Flowchart of a for loop


for ( initialization ; condition ; increment ) statement;

initialization

condition evaluated
true statement increment false

The for Statement


for ( initialization ; condition ; increment ) statement;

A for loop is equivalent to the following while loop structure:


initialization; while ( condition ) { statement; increment; }

The for Statement: Example


int sum = 0; for (int counter = 1; counter <= max; counter++) sum += counter; // beginning of the next statement

Establish initial value of control variable.

int counter = 1

Determine if final value of control variable has been reached.

counter <= max

true

sum+= counter

counter++ Increment the control variable.

false

Body of loop (this may be multiple statements)

Summary: Loop Statements Syntax


while statement
while ( condition ) statement;

do {

do statement

statement list; } while ( condition );

for ( initialization ; condition ; increment ) statement;

for statement

Comments about Loop Statements


Choosing which loop statement to use will depend on the specific situation and personal taste Checking and updating the condition
in most cases, the body of a loop must eventually make the condition false
if not, it is an infinite loop, which will execute until the user interrupts the program
Ctrl-C in command line

this is a common type of logical error, and you should always double check to ensure that your loops will terminate normally

pay attention to the condition to avoid an off by 1 problem


15

Designing a Loop: A (Rough) Template


Think of state (captured by variables) that you need to keep track across multiple iterations
e.g., counter, sum e.g., boolean variables: thisRoundIsOver, canBeDivided

Initialize state (variables) Inside the loop


process
the processing may depend on the current state

update state
e.g., increase the counter, add to sum, set the flag

Termination condition: in general, it is a boolean expression involving the state variables

Example: Check if a Number is Prime


// check if a positive integer n is prime boolean canBeDivided = false; for (int i = 2; i < n && !canBeDivided; i++) { if (n % i == 0) canBeDivided = true; } if (!canBeDivided) { System.out.println (n + is not a prime!); } else { System.out.println (n + is a prime!); }

Example: Reverse a Number


number reverse

1 2 3 4 5 6 7

7 6 5 4 3 2 1

number

reverse

1 2 3 4 5

7 6

The state is captured by number and reverse.

Example: Reverse a Number


number % 10 reverse = reverse * 10 + number % 10

number

reverse

1 2 3 4 5

7 6 5

int intReverse (int number) { int reverse , lastDigit; reverse = 0; while (number > 0) { lastDigit = number % 10; reverse = reverse * 10 + lastDigit; number = number / 10; } }

Example: Reverse a Number


number reverse

1 2 3 4

7 6 5

reverse = 0; while (number > 0) { lastDigit = number % 10; reverse = reverse * 10 + lastDigit; number = number / 10; }

Example: Play Games


// initialize global state variables // such as statistics boolean userQuits = false; do { // initialize state variables for one game // such as number of guesses allowed boolean thisRoundIsOver = false; do { // get user input // process input, update states // determine if thisRoundIsOver // userQuits implies thisRoundIsOver } while ( !thisRoundIsOver ); // update statistics of preceding game } while ( !userQuits ); // report total statistics

Using Break: Loop-and-a-Half Idiom


Initialize total to zero Initialize counter to zero Input the first grade (possibly the sentinel) While (true) While (grade != sentinel) { Add this grade into the running total Add one to the grade counter Input next grad (possibly the sentinel) } If the counter is not equal to zero Set the average to the total divided by the counter Print the average Else Print No grades were entered
{

Initialize total to zero Initialize counter to zero

Input next grade (possibly the sentinel) If ( the user has entered the sentinel) break; Add this grade into the running total Add one to the grade counter } If the counter is not equal to zero Set the average to the total divided by the counter Print the average Else Print No grades were entered

Exercise : AverageGrade
Write a program to compute the average of a sequence of (numerical) student grades entered by the user
If the user types something else than a number between 0.0 and 4.0, the program should abort.

23

Exercise : Reverse a Number


Write a program that outputs a reverse of the positive integers the user types.
If the user types something else, the program should abort.

Exercise : PalindromeTester
Write a program to read in a sequence of strings; for each string, determine whether it is a palindrome

25

Exercise : Stars
Write a program to print a triangle formed by * * ** *** The program should read in the number of rows from the user; the row should be between 1 to 10

Methods

Methods
A useful program can be long and contains many statements A method groups a sequence of statements and should provide a well-defined, easy-to-understand functionality
a method takes input, performs actions, and produces output

Recall: In Java, each method is defined within specific class

Method Declaration: Header


A method declaration begins with a method header
class MyClass {
static int min ( int num1, int num2 )

parameter list method name The parameter list specifies the type and name of each parameter return type The name of a parameter in the method properties declaration is called a formal argument

Method Declaration: Body


The header is followed by the method body:
class MyClass { static int min(int num1, int num2) { int minValue = num1 < num2 ? num1 : num2; return minValue; } }

The return Statement


The return type of a method indicates the type of value that the method sends back to the calling location
A method that does not return a value has a void return type

The return statement specifies the value that will be returned


Its expression must conform to the return type
31

Calling a Method
Each time a method is called, the values of the actual arguments in the invocation are assigned to the formal arguments
int num = min (2, 3);

static int min (int num1, int num2) { int minValue = (num1 < num2 ? num1 : num2); return minValue; }

Method Overloading
A class may define multiple methods with the same name---this is called method overloading
usually perform the same task on different data types

Example: The PrintStream class defines multiple println methods, i.e., println is overloaded:
println (String s) println (int i) println (double d)

The following lines use the System.out.print method for different data types:
System.out.println ("The total is:"); double total = 0; System.out.println (total);
33

Method Overloading: Signature


The compiler must be able to determine which version of the method is being invoked This is by analyzing the parameters, which form the signature of a method
the signature includes the type and order of the parameters
if multiple methods match a method call, the compiler picks the best match if none matches exactly but some implicit conversion can be done to match a method, then the method is invoke with implicit conversion.

the return type of the method is not part of the signature

34

Method Overloading
Version 1 double tryMe (int x) { return x + .375; } Version 2

double tryMe (int x, double y) { return x * y; }

Invocation result = tryMe (25, 4.32)

More Examples
double tryMe ( int x ) { return x + 5; } double tryMe ( double x ) { return x * .375; }
Which tryMe will be called?

tryMe( 1 );

tryMe( 1.0 );
tryMe( 1.0, 2); tryMe( 1, 2);

double tryMe (double x, int y) { return x + y; }

tryMe( 1.0, 2.0);

Variable Scoping

Three variable types


There are can be three types of variables in a method
local variables
those declared in the method

formal arguments

class variables
those defined in the class but not in the method

Example of Variable Types


public class Box { private int length, width;

public int widen (int extra_width) { private int temp1; size += extra_width; } public int lenghten (int extra_lenth) { private int temp2; size += extra_length; }
}

class variables formal arguments local variables

Scope of Variables
public class Box { private int length, width;

public int widen (int extra_width) { private int temp1; size += extra_width; } public int lenghten (int extra_lenth) { private int temp2; size += extra_length; }
}

Class variables are valid in all methods of the class A formal argument is valid within its method Local variables are valid from the point of declaration to the end of the enclosing block

Two Types of Parameter Passing


If a modification of the formal argument has no effect on the actual argument,
it is call by value

If a modification of the formal argument can change the value of the actual argument,
it is call by reference

Call-By-Value and Call-By-Reference in Java


Depend on the type of the formal argument If a formal argument is a primitive data type, a modification on the formal argument has no effect on the actual argument
this is call by value, e.g. num1 = min(2, 3); num2 = min(x, y);

If a formal argument is not a primitive data type, an operation on the formal argument can change the actual argument
this is call by reference more discussion in the later part of the course

Anda mungkin juga menyukai