Looping Constructs 5.5 5.8 - PowerPoint PPT Presentation

1 / 15
About This Presentation
Title:

Looping Constructs 5.5 5.8

Description:

for example, our 'calculator' application that prompts for a number and an ... But we can still only execute that calculation once. what if we wanted the option ... – PowerPoint PPT presentation

Number of Views:51
Avg rating:3.0/5.0
Slides: 16
Provided by: Steve57
Category:

less

Transcript and Presenter's Notes

Title: Looping Constructs 5.5 5.8


1
Looping Constructs (5.5 5.8)
  • Conditionals allow us to build computations that
    depend on input values
  • for example, our calculator application that
    prompts for a number and an operation the does a
    calculation
  • But we can still only execute that calculation
    once
  • what if we wanted the option of doing more than
    one calculation
  • Loops let the number of calculations depend on
    input values as well
  • do this 100 times (where 100 is an input)
  • do this until there is no more input
  • do this until the user (or other input) tells you
    to stop
  • do this while there is still space in the table
    to hold the result
  • do this until I have at least 5 successful runs
  • The general form is
  • do this calculation while some value is true
  • do this calculation until some value is true
  • (do this calculation while some value is false)

2
A Little History Loops IF GOTO
  • 050 PRINT "Give me two positive numbers to add "
  • 100 READ X
  • READ Y
  • IF (X gt 0 Y gt 0) GOTO 300
  • PRINT "Invalid numbers, try again."
  • GOTO 400
  • PRINT X Y
  • 400 PRINT "Another addition?"
  • 500 READ ANSWER
  • 600 IF (ANSWER "Y") GOTO 050

MORE TRUE WHILE (MORE) PRINT "Give me two
positive numbers to add " READ X READ Y
IF (X lt 0 Y lt 0) PRINT "Invalid
numbers, try again." ELSE PRINT X
Y PRINT "Another addition?" READ
ANSWER MORE (ANSWER "Y")
3
The while statement
while (true) System.out.println(Stop me!)
while (boolean-expression) statements
while (false) System.out.println(Start
me!)
while (userWantsToContinue) getUserInput()
doCalculation() askToContinue()
while (fileHasRecords()) getLineFromFile()
processLine()
while ((trials lt 1000) (successes lt 10))
doTrial()
while (counter lt 100) doSomethingToElement(co
unter)
4
Basic Types of Loops
  • User input loop
  • user types in string print it in upper case
  • user types in two numbers on a line report the
    sum
  • user types in sequence of integers report the
    sum
  • how is the length of the list communicated?
  • calculator example
  • Loop over a collection of objects
  • all lines in a file
  • file contains a sequence of integers
  • report the sum
  • report the maximum
  • report whether all the integers are positive
  • report whether the sequence is in ascending order
  • all characters in a string
  • how many whitespace characters are there?
  • is every character a digit?
  • Loop until some condition holds
  • given the file of integers, produce 2 that are
    divisible by 2

5
Sentinels versus Loop breaks
  • In every loop there is some point at which you
    calculate the termination condition
  • in a user input loop you ask the user (and get
    y or n or an empty line)
  • in a file loop, you ask whether the file has more
    lines
  • in a loop over a sequence, you ask whether you
    are at the end of the sequence
  • in other loops, you see whether you have produced
    enough results
  • It is a common programming idiom to assign this
    termination condition (a boolean value) to a
    variable
  • the variable is called a sentinel variable
  • the termination clause in the while loop refers
    (only) to this variable

6
Sentinels in Action
boolean fileHasInput aScanner.hasNext() while
(fileHasInput) String nextLine
aScanner.nextLine() processLine(nextLine)
fileHasInput aScanner.hasNext()
boolean fileHasInput aScanner.hasNext() while
(aScanner.hasNext()) String nextLine
aScanner.nextLine() processLine(nextLine)
boolean continue true while (continue)
String nextLine aScanner.nextLine()
processLine(nextLine) System.out.print(Quit?
) String response aScanner.next() continue
!response.equals(yes)
7
When Sentinels Get Awkward (the case for break)
boolean continue true while (continue)
System.out.print(Another? ) String response
aScanner.next() if (response.equals(yes))
continue true processCommand() else
continue false
while (true) System.out.print(Another? ) if
((aScanner.next()).equals(yes)) break
processCommand()
8
The for loop
  • The for loop adds no power to the language (only
    convenience)

for (int i 0 i lt 100 i )
System.out.println(i)
int i 0 while (i lt 100) System.out.println(
i) i
9
For loop and other sequences
String s "HEllO wOrLD!" int upperCaseCount
0 for (int i 0 i lt s.length() i ) if
(Character.isUpperCase(s.charAt(i)))
upperCaseCount 1 System.out.println(
upperCaseCount)
10
The for loop and multiple clauses
String s1 "Hello world" String s2 "dlrow
olleH" boolean mirror true if (s1.length()
! s2.length()) mirror false else
for (int i0, j s2.length() - 1 i lt
s1.length() i, j--) if (s1.charAt(i)
! s2.charAt(j)) mirror false
break if (mirror)
System.out.println("Strings are mirrors") else
System.out.println("Strings are NOT
mirrors")
11
Nested Loops
  • Often times when you have two variables "looping"
    at once, you really want a nested loop
  • For each line in a file, count the upper-case
    characters
  • loop over all lines, and for each line loop over
    characters in that line
  • For each character in a string, count the
    instances of that character in another string
  • loop over all characters in the first string
    for each character loop over the other string
  • For each number between 1 and 100, compute the
    factorial
  • loop over 1 to 100, and for each number loop over
    all smaller numbers
  • (Do each of these examples.)

12
Collections and the Iterator Interface
  • Terminology
  • Collection is an abstract term to refer to any
    collection of objects (a set, a sequence)
  • a String is a collection of characters
  • a file is a collection of Strings (one String per
    line)
  • a string can also be viewed as a collection of
    tokens
  • Remember the Scanner class and the concept of
    tokens

T
h
i
s
s
t
r
i
n
g
\n
\n

h
a
s


5

\t

t
o
k
e
n
s
.
.
.
\n
(The String also has three lines. The String
also has 33 characters.)
13
Accessing Collections
  • We access the String collection positionally (by
    index). That is, we can ask for the 3rd element
    in the collection (3rd character in the String)
    without having to go through the 1st or 2nd
    character to get there
  • Not all collections allow positional access. For
    example, a File is a collection of Strings, but
    you can't look at (read) the 3rd line of the file
    until you have first read the first two.
  • This is called sequential or iterator access of
    the collection. You get all of the elements
    through two methods
  • do you have a next element?
  • give me the next element
  • Many classes in Java agree to give these two
    (actually three) methods common names
  • boolean hasNext()
  • Object next()
  • void remove()

14
The Iterator Interface
  • Any collection class that allows this kind of
    access (that implements these methods) is called
    an Iterator
  • this might apply to a collection of Strings or of
    Numbers or of Employees or of Students so the
    iterator convention just returns an Object
  • String does not implement this interface
  • that is, there is no hasNext() or next() methods
    implemented as part of the String class
  • but it is extremely easy to implement it
  • Scanner does implement this interface and this is
    how the idiom looks

Scanner s new Scanner("This string\n\nhas
five(5) \ttokens...\n") while (s.hasNext())
String nextToken (String)s.next()
System.out.println(nextToken)
15
Quick Diversion Two Ways to Traverse a File
public static String FILE_NAME
"test.txt" public static void
readFileWithScanner() throws Exception
Scanner s new Scanner(new File(FILE_NAME))
int lineCount 1 while (s.hasNext())
String nextLine s.nextLine()
System.out.println(lineCount " " nextLine)
lineCount public static void
readFileNoScanner() throws Exception
BufferedReader br new BufferedReader(new
FileReader(FILE_NAME)) String nextLine
br.readLine() int lineCount 1 while
(nextLine ! null) System.out.println(line
Count " " nextLine) lineCount
nextLine br.readLine()
Write a Comment
User Comments (0)
About PowerShow.com