chapter 6a while loops asserting java © rick mercer

17
Chapter 6A Chapter 6A While Loops While Loops Asserting Java Asserting Java © Rick Mercer © Rick Mercer

Upload: randell-martin

Post on 04-Jan-2016

216 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: Chapter 6A While Loops Asserting Java © Rick Mercer

Chapter 6AChapter 6A

While LoopsWhile Loops

Asserting JavaAsserting Java © Rick Mercer© Rick Mercer

Page 2: Chapter 6A While Loops Asserting Java © Rick Mercer

Algorithmic Pattern: Algorithmic Pattern: The Determinate loopThe Determinate loop

We often need to perform some action a specific We often need to perform some action a specific number of times: number of times: —Produce 89 paychecks.Produce 89 paychecks.

—Count down to 0 (take 1 second of the clock).Count down to 0 (take 1 second of the clock).

—Compute grades for 81 studentsCompute grades for 81 students

TheThe determinate loop determinate loop pattern repeats some action pattern repeats some action a specific number of times.a specific number of times.

Page 3: Chapter 6A While Loops Asserting Java © Rick Mercer

Pattern: Determinate Loop

Problem: Do something exactly n times, where n is known in advance.

Algorithm determine n repeat the following n times { perform these actions }

Code Example:

System.out.print("Enter n: "); int n = keyboard.nextInt(); int count = 1; while(count <= n) { System.out.print("Enter number: "); number = keyboard.nextInt(); sum = sum + number; count = count + 1; }

Page 4: Chapter 6A While Loops Asserting Java © Rick Mercer

Determinate LoopsDeterminate Loops

The determinate loop pattern can be implemented with The determinate loop pattern can be implemented with the Java while loopthe Java while loop

This template executes some statements n times:This template executes some statements n times:

— determinate loopsdeterminate loops must know the number of repetitions must know the number of repetitions beforebefore they begin: know exactly how many employees, or students, or they begin: know exactly how many employees, or students, or whatever that must be processed, for examplewhatever that must be processed, for example

int n = 0; /* how often we must repeat */ int counter = 1; while (counter <= n) { // TODO: Add the steps to be repeated counter = counter + 1; }

Page 5: Chapter 6A While Loops Asserting Java © Rick Mercer

While loop outputWhile loop output

What is the output?What is the output?

int j = 1; int n = 5; while (j <= n) { System.out.print(j + " "); j = j + 1; }

j = 2 * n; while (j >= 0) { System.out.print(j + " "); j = j - 2; }

Page 6: Chapter 6A While Loops Asserting Java © Rick Mercer

Problem SolvingProblem SolvingThe Fibonacci numbers are a sequence of integers in which the first two elements are 1, and each following element is the sum of the two preceding elements. Write int fib(int n) to return the nth Fibonacci number.

@Test public void testFib() { LoopFun loops = new LoopFun(); assertEquals(1, loops.fib(1)); assertEquals(1, loops.fib(2)); assertEquals(2, loops.fib(3)); assertEquals(3, loops.fib(4)); assertEquals(5, loops.fib(5)); assertEquals(8, loops.fib(6)); assertEquals(13, loops.fib(7)); assertEquals(21, loops.fib(8)); }

Page 7: Chapter 6A While Loops Asserting Java © Rick Mercer

Indeterminate LoopsIndeterminate Loops

Determinate loops have a limitationDeterminate loops have a limitation—We must know n (the number of repetitions) in We must know n (the number of repetitions) in

advanceadvance

Many situations need us to repeat a set of Many situations need us to repeat a set of statements an unspecified number of times: statements an unspecified number of times: —Processing report cards for every student in a school Processing report cards for every student in a school

(or paychecks for all employees, or...)(or paychecks for all employees, or...)—Allowing 1 to many ATM transactionsAllowing 1 to many ATM transactions—Asking the user for specific input and allowing re-entry Asking the user for specific input and allowing re-entry

of input after invalid inputsof input after invalid inputs

Page 8: Chapter 6A While Loops Asserting Java © Rick Mercer

Change DeterminateLoop.java to Change DeterminateLoop.java to an indeterminate loop:an indeterminate loop:

Sometimes a stream of input from the Sometimes a stream of input from the keyboard or a file needs to be read until there keyboard or a file needs to be read until there is no more data in the input streamis no more data in the input stream

Consider using a special value of the same Consider using a special value of the same type that is not meant to be processedtype that is not meant to be processed—Perhaps a negative integer for tests that range from Perhaps a negative integer for tests that range from

0 through 100 only0 through 100 only

—Code Demo: Change DeterminateLoop to read until Code Demo: Change DeterminateLoop to read until there is a sentinel (like things we will do in lab)there is a sentinel (like things we will do in lab)

Page 9: Chapter 6A While Loops Asserting Java © Rick Mercer

Some things that terminate Some things that terminate indeterminate loopsindeterminate loops

An An indeterminate loop indeterminate loop repeats a process until some repeats a process until some stopping event terminates the repetitionstopping event terminates the repetition

There are many such events, but we'll focus on these:There are many such events, but we'll focus on these:—User enters a special value indicating end of dataUser enters a special value indicating end of data—A logical expression becomes falseA logical expression becomes false— The Grid's mover hits the wall or an edgeThe Grid's mover hits the wall or an edge— The end of a file is encounteredThe end of a file is encountered

Indeterminate loops do not need to know n in advanceIndeterminate loops do not need to know n in advance

Indeterminate loops can actually determine nIndeterminate loops can actually determine n

Page 10: Chapter 6A While Loops Asserting Java © Rick Mercer

Pattern Indeterminate loop

Problem Some process must repeat an unknown number of times so some event is needed to terminate

the loop.

Algorithm while( the termination event has not occurred ) { Execute these actions bring the loop closer to termination

}

Code while(myGrid.frontIsClear()) {Example myGrid.move( );

}

Page 11: Chapter 6A While Loops Asserting Java © Rick Mercer

// Using random robot placement, instruct the // robot to get to the wall in front.//// This program needs Grid.java in the same project//public class MoveAroundTheGrid {

public static void main(String[] args) { // When using this 2 argument constructor, the // grid is surrounded by blocks with one "exit" // and the mover is facing a random direction // after being placed in a random location. Grid g = new Grid(10, 15);

// Always get to a wall or the lone exit if lucky while (g.frontIsClear()) { g.move(); } }}

Page 12: Chapter 6A While Loops Asserting Java © Rick Mercer

While loop with a Scanner While loop with a Scanner

Sometimes a stream of input from the Sometimes a stream of input from the keyboard or a file needs to be read until there keyboard or a file needs to be read until there is no more data in the input streamis no more data in the input stream

Consider a Scanner object constructed with a Consider a Scanner object constructed with a String argument String argument —The string represents an input streamThe string represents an input stream

You will need Scanner in projectYou will need Scanner in project

Page 13: Chapter 6A While Loops Asserting Java © Rick Mercer

These assertions passThese assertions pass

@Test public void showScanner() { Scanner scannerWithInts = new Scanner("1 2 3"); assertEquals(1, scannerWithInts.nextInt()); assertEquals(2, scannerWithInts.nextInt()); assertEquals(3, scannerWithInts.nextInt());

Scanner scanner = new Scanner("There are five words here."); assertEquals("There", scanner.next()); assertEquals("are", scanner.next()); assertEquals("five", scanner.next()); assertEquals("words", scanner.next()); assertEquals("here.", scanner.next()); }

Page 14: Chapter 6A While Loops Asserting Java © Rick Mercer

A test method to test num100sA test method to test num100s

@Test public void testNum100s() { LoopFun lf = new LoopFun(); Scanner scanner0 = new Scanner("1 2 3"); Scanner scanner1 = new Scanner("4 100 2 5"); Scanner scanner3 = new Scanner("100 100 2 -3 5 3 2 -100 100");

assertEquals(0, lf.num100s(scanner0)); assertEquals(1, lf.num100s(scanner1)); assertEquals(3, lf.num100s(scanner3)); }

Page 15: Chapter 6A While Loops Asserting Java © Rick Mercer

AnswerAnswer

public int num100s (Scanner scanner) { int result = 0; while (scanner.hasNextInt()) { int next = scanner.nextInt(); if (next == 100) result++; } return result; }

Page 16: Chapter 6A While Loops Asserting Java © Rick Mercer

Careful using next too often!Careful using next too often!

These assertions should pass with the code that These assertions should pass with the code that follows on the next slidefollows on the next slide

@Test public void testSumOfNegs() { ControlFun lf = new ControlFun(); Scanner scanner0 = new Scanner("1 2 3"); Scanner scannerA = new Scanner("1 -2 3"); Scanner scannerB = new Scanner("-4 1 -2 3");

assertEquals(0, lf.sumOfNegatives(scanner0)); assertEquals(-2, lf.sumOfNegatives(scannerA)); assertEquals(-6, lf.sumOfNegatives(scannerB)); }

Page 17: Chapter 6A While Loops Asserting Java © Rick Mercer

What's wrong with this method?What's wrong with this method?

public int sumOfNegatives(Scanner scanner) { int result = 0;

while (scanner.hasNextInt()) { if (scanner.nextInt() < 0) { result += scanner.nextInt(); } }

return result; }