Download presentation
Presentation is loading. Please wait.
Published byTania Laflin Modified over 10 years ago
1
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 3: Program Statements 3.6 – Iterators – p.146-150
2
© 2011 Pearson Education, publishing as Addison-Wesley 2 Iterators An iterator is an object that has methods that allow you to process a collection of items one at a time The hasNext and next methods are used to loop through the collection Several classes in the Java class library define iterator objects, including Scanner while (myCollection.hasNext()) { System.out.println(myCollection.next()); }
3
© 2011 Pearson Education, publishing as Addison-Wesley 3 Iterators – examples import java.util.Scanner; import java.io.*; public class URLDissector public static void main (String[ ] args) throws IOException The IOException clause in the main method header allows the computer to throw an error if there is a problem finding or opening the input file. String url; Scanner fileScan, urlScan; fileScan = newScanner (new File (“urls.inp”)); URLDissector.java (page 148) has the following code:
4
© 2011 Pearson Education, publishing as Addison-Wesley 4 What separates each item in an input file? You can customize the delimiter as in URLDissector.java: urlScan = new Scanner (url); urlScan.useDelimiter(“/”); By default, a Scanner object assumes that white space is the delimiter (spaces, tabs and new lines) that separates items in a file. Each iteration through the loop reads one line (one URL) from the input file and prints it out. For each URL, a new Scanner object is set up to parse the pieces of the URL string which is passed to the Scanner constructor when instantiating the URLScan object.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.