Package org.cis1200

Class LineIterator

java.lang.Object
org.cis1200.LineIterator
All Implemented Interfaces:
Iterator<String>

public class LineIterator extends Object implements Iterator<String>
LineIterator provides a useful wrapper around Java's provided BufferedReader and provides practice with implementing an Iterator. Your solution should not read the entire file into memory at once, instead reading a line whenever the next() method is called.

Notes: - Any IOExceptions thrown be caught and handled properly. - Do not use the ready() method from BufferedReader.

  • Constructor Details Link icon

    • LineIterator Link icon

      public LineIterator(BufferedReader reader)
      Constructs a LineIterator for reader. Feel free to create and instantiate any variables that your implementation requires here. See recitation and lecture notes for guidance.

      If an IOException is thrown by the BufferedReader, then hasNext should return false.

      The only method that should be called on BufferedReader is readLine() and close(). You cannot call any other methods.

      Parameters:
      reader - - A reader to be turned to an Iterator
      Throws:
      IllegalArgumentException - if reader is null
    • LineIterator Link icon

      public LineIterator(String filePath)
      Creates a LineIterator from a provided filePath by creating a FileReader and BufferedReader for the file.

      This constructor is implemented for you. DO NOT MODIFY THIS CONSTRUCTOR.

      Parameters:
      filePath - - a string representing the file
      Throws:
      IllegalArgumentException - if filePath is null or if the file doesn't exist
  • Method Details Link icon

    • hasNext Link icon

      public boolean hasNext()
      Returns true if there are lines left to read in the file, and false otherwise.

      If there are no more lines left, this method attempts to close the BufferedReader. In case of an IOException during the closing process, an error message is printed to the console indicating the issue.

      Specified by:
      hasNext in interface Iterator<String>
      Returns:
      a boolean indicating whether the LineIterator can produce another line from the file
    • next Link icon

      public String next()
      Returns the next line from the file, or throws a NoSuchElementException if there are no more strings left to return (i.e. hasNext() is false).

      This method also advances the iterator in preparation for another invocation. If an IOException is thrown during a next() call, your iterator should make note of this such that future calls of hasNext() will return false and future calls of next() will throw a NoSuchElementException

      Specified by:
      next in interface Iterator<String>
      Returns:
      the next line in the file
      Throws:
      NoSuchElementException - if there is no more data in the file