Grouping Objects 2 Collections and the for-each loop Collections and the while loop.
-
date post
21-Dec-2015 -
Category
Documents
-
view
221 -
download
0
Transcript of Grouping Objects 2 Collections and the for-each loop Collections and the while loop.
Grouping Objects 2
Collections and the for-each loopCollections and the for-each loop
Collections and the while loopCollections and the while loop
Main concepts to be covered
(Collections: the(Collections: the ArrayListArrayList))
Iteration: theIteration: the for-each for-each looploop
Iteration: theIteration: the while while looploop
• We often want to perform some We often want to perform some actions an arbitrary number of times.actions an arbitrary number of times.
• Most programming languages include Most programming languages include loop statementsloop statements to make this possible. to make this possible.
• Java has several kinds of loop Java has several kinds of loop statement.statement.
For example, print all the notes in the For example, print all the notes in the notebook. But how many are there?notebook. But how many are there?For example, print all the notes in the For example, print all the notes in the notebook. But how many are there?notebook. But how many are there?
We will start with itsWe will start with its for-each for-each looploop..We will start with itsWe will start with its for-each for-each looploop..
Iteration
• We often want to repeat the same We often want to repeat the same action on action on eacheach object in a object in a collectioncollection..
• The The for-each for-each loop provides a simple loop provides a simple way to do this.way to do this.
Iteration (Iteration (for-eachfor-each))
The The for-eachfor-each Loop Loop
for (for (ElementTypeElementType elementelement :: collectioncollection) {) { ... loop body... loop body} }
for keyword
Statement(s) to be repeated
General form of the for-each loop
loop header
For each element in collection, do the things in the loop body.
Pseudo-code expression of the actions of a for-each loop
/**/** * List all notes in the notebook.* List all notes in the notebook. */*/public void listNotes()public void listNotes(){{ for (for (StringString notenote : : notesnotes) {) { System.out.println (System.out.println (notenote);); }}} }
for each note in notes, print out note.
A Method in NoteBook
Must be an Must be an object of a object of a collectioncollection
class – such as class – such as ArrayListArrayList<String><String>
Pseudo-code expression of the actions of the above for-each loop
Review
• So, loop statements enable a block of statements to be repeated.
• The for-each loop enables iteration over each element from a collection.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
The The whilewhile Loop Loop
• A A for-eachfor-each loop repeats the loop body loop repeats the loop body for each object in a collection.for each object in a collection.
• Sometimes we require more variation Sometimes we require more variation than this.than this.
• We can use a We can use a boolean conditionboolean condition to to decide whether or not to keep going.decide whether or not to keep going.
• A A whilewhile loop provides this control.loop provides this control.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
while (while (loop conditionloop condition) {) { ... ... loop bodyloop body} }
while the loop condition is true, do the things in the loop body.
boolean testwhile keyword
Statements to be repeated
Pseudo-code expression of the actions of a while loop
General form of a while loop
The The whilewhile Loop Loop
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
/**/** * List all notes in the notebook.* List all notes in the notebook. */*/public void listNotes()public void listNotes(){{ int index = 0;int index = 0; while (while (index < notes.size()index < notes.size()) {) { System.out.println (notes.get(index));System.out.println (notes.get(index)); index++;index++; }}} }
while the value of index is less than the size of the collection, do print the note at position index and, then, increment index.
Pseudo-code expression of the actions of the above while loop
(Increment index by 1)index = index + 1
A Method in NoteBookalternative
alternative codingcoding
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
/**/** * List all notes in the notebook.* List all notes in the notebook. */*/public void listNotes()public void listNotes(){{ for (for (StringString notenote : : notesnotes) {) { System.out.println (System.out.println (notenote);); }}} }
for each note in notes, print out note.
A Method in NoteBook
Pseudo-code expression of the actions of the above for-each loop
previous
previous codingcoding
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
for-eachfor-each versus versus whilewhile• for-eachfor-each::
• can only be used for loops involving a can only be used for loops involving a collectioncollection• easier to writeeasier to write• safer: it is guaranteed to stopsafer: it is guaranteed to stop• actually, we don’t actually, we don’t havehave to process the whole to process the whole
collection collection (we’ll show this presently)(we’ll show this presently)
• whilewhile::• can be used for loops that do not involve a can be used for loops that do not involve a
collectioncollection• take care: the loop may never end!take care: the loop may never end!• used on a collection class, we don’t used on a collection class, we don’t havehave to to
process all of it process all of it (we’ll show this presently)(we’ll show this presently)
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
whilewhile loop loop (not on a (not on a collection)collection)
int index = 0;int index = 0;while (while (index <= 42index <= 42) {) { System.out.println(index);System.out.println(index); index = index + 2;index = index + 2;}}
int index = 0;int index = 0;while (while (index >= 42index >= 42) {) { System.out.println(index);System.out.println(index); index = index + 2;index = index + 2;}}
int index = 0;int index = 0;while (while (index <= 42index <= 42) {) { System.out.println(index);System.out.println(index); index = index - 2;index = index - 2;}}
// Print all even numbers from 0 to 42 inclusive.// Print all even numbers from 0 to 42 inclusive.
// Programming error? This does nothing at all!// Programming error? This does nothing at all!
// Programming error? This loop never ends!// Programming error? This loop never ends!
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Searching a Collection/**/** * Search all notes in the notebook for the first* Search all notes in the notebook for the first * one * one containingcontaining a specified piece of text. a specified piece of text. * * * @param searchString The sought text * @param searchString The sought text * @return The index of the note containing the text * @return The index of the note containing the text * (if none found, return -1) * (if none found, return -1) */*/public int searchNotes (String public int searchNotes (String searchStringsearchString)){{ ... code body of the method... code body of the method} }
-1 -1 is not a valid index for a collection. So if that it what is returned, is not a valid index for a collection. So if that it what is returned, it means no note containing the search string was found. Otherwise, it means no note containing the search string was found. Otherwise, the number returned will be a valid index (between the number returned will be a valid index (between 00 and and one less one less than the size of the notebookthan the size of the notebook).).
-1 -1 is not a valid index for a collection. So if that it what is returned, is not a valid index for a collection. So if that it what is returned, it means no note containing the search string was found. Otherwise, it means no note containing the search string was found. Otherwise, the number returned will be a valid index (between the number returned will be a valid index (between 00 and and one less one less than the size of the notebookthan the size of the notebook).).
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
public int searchNotes (String public int searchNotes (String searchStringsearchString)){{ int index = 0;int index = 0; boolean found = false; boolean found = false; // so far, not found it// so far, not found it while ((while ((!found!found) ) &&&& ( (index < notes.size()index < notes.size())) {)) { String note = notes.get(index);String note = notes.get(index); if (note.contains(searchString)) {if (note.contains(searchString)) { // stop here - no need to keep looking.// stop here - no need to keep looking. found = true;found = true; }} else {else { index++; index++; // index = index + 1// index = index + 1 }} }} if (found) {return if (found) {return indexindex;} else {return ;} else {return -1-1;};}}}
Either weEither we foundfound a note containing the search string (in which casea note containing the search string (in which case indexindex tells us which one) ...tells us which one) ...Either weEither we foundfound a note containing the search string (in which casea note containing the search string (in which case indexindex tells us which one) ...tells us which one) ...
Or we searched the whole collection, didn’t find it andOr we searched the whole collection, didn’t find it and foundfound is still is still false (andfalse (and indexindex is is notes.size()notes.size(), which is not a valid index)., which is not a valid index).Or we searched the whole collection, didn’t find it andOr we searched the whole collection, didn’t find it and foundfound is still is still false (andfalse (and indexindex is is notes.size()notes.size(), which is not a valid index)., which is not a valid index).
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Either weEither we foundfound a note containing the search string (in which case a note containing the search string (in which case we returned thewe returned the indexindex telling us which one) ...telling us which one) ...Either weEither we foundfound a note containing the search string (in which case a note containing the search string (in which case we returned thewe returned the indexindex telling us which one) ...telling us which one) ...
Or we searched the whole collection, didn’t find it andOr we searched the whole collection, didn’t find it and returned returned -1-1..Or we searched the whole collection, didn’t find it andOr we searched the whole collection, didn’t find it and returned returned -1-1..
public int searchNotes (String public int searchNotes (String searchStringsearchString)){{ int index = 0;int index = 0; while (while (index < notes.size()index < notes.size()) {) { String note = notes.get(index);String note = notes.get(index); if (note.contains(searchString)) {if (note.contains(searchString)) { // stop here - no need to keep looking.// stop here - no need to keep looking. return index;return index; }} else {else { index++; index++; // index = index + 1// index = index + 1 }} }} return return -1-1;;}}
alternative
alternative coding 1
coding 1
exits the method, jumping exits the method, jumping straight out of the loop!straight out of the loop!
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Either weEither we foundfound a note containing the search string (in which case a note containing the search string (in which case we returned thewe returned the indexindex telling us which one) ...telling us which one) ...Either weEither we foundfound a note containing the search string (in which case a note containing the search string (in which case we returned thewe returned the indexindex telling us which one) ...telling us which one) ...
Or we searched the whole collection, didn’t find it andOr we searched the whole collection, didn’t find it and returned returned -1-1..Or we searched the whole collection, didn’t find it andOr we searched the whole collection, didn’t find it and returned returned -1-1..
public int searchNotes (String public int searchNotes (String searchStringsearchString)){{ int index = 0;int index = 0; for (for (String note : notesString note : notes) {) { if (note.contains(searchString)) {if (note.contains(searchString)) { // stop here - no need to keep looking.// stop here - no need to keep looking. return index;return index; }} else {else { index++; index++; // index = index + 1// index = index + 1 }} }} return return -1-1;;}}
alternative
alternative coding 2
coding 2
exits the method, jumping exits the method, jumping straight out of the loop!straight out of the loop!
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
• looploop statements enable a block statements enable a block of statements to be repeated.of statements to be repeated.
• The The for-eachfor-each loop enables loop enables iteration over a whole collection.iteration over a whole collection.
• The The whilewhile loop enables iteration loop enables iteration over over partpart of a collection … or for of a collection … or for iteration that doesn’t involveiteration that doesn’t involve a a collectioncollection..
Review
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Review
• The The for-eachfor-each loop enables iteration loop enables iteration over a whole collection.over a whole collection.
Actually, by using aActually, by using a returnreturn, a, a for-eachfor-each loop can loop can have an early exit – thus, enabling iteration overhave an early exit – thus, enabling iteration over (the first) part(the first) part of a collection.of a collection.
Actually, by using aActually, by using a returnreturn, a, a for-eachfor-each loop can loop can have an early exit – thus, enabling iteration overhave an early exit – thus, enabling iteration over (the first) part(the first) part of a collection.of a collection.
**
**
For our For our searchNotessearchNotes example, this happens to example, this happens to yield the simplest coding …yield the simplest coding …For our For our searchNotessearchNotes example, this happens to example, this happens to yield the simplest coding …yield the simplest coding …