package rebelsky.cs362;

/**
 * A stream of characters built from a string.  
 *
 * @author Samuel A. Rebelsky
 * @version 0.2 of October 2002
 */
public class StringCharStream 
  implements CharStream
{
  // +--------+-------------------------------------------------------------
  // | Fields |
  // +--------+

  /**
   * The string which serves as the basis of the stream.
   */
  private String str;

  /**
   * The index of the current character in that string.
   */
  private int pos;

  /**
   * The length of the string.
   */
  private int length;


  // +--------------+-------------------------------------------------------
  // | Constructors |
  // +--------------+

  /**
   * Build a new character stream that streams the characters in
   * string basis.
   */
  public StringCharStream(String basis) {
    this.str = basis;
    this.pos = 0;
    this.length = this.str.length();
  } // StringCharStream


  // +-----------+----------------------------------------------------------
  // | Observers |
  // +-----------+

  /**
   * Determine if any more characters remain in the stream.
   *
   * Pre: (none).
   * Post: Returns true if characters remain and false o/w.
   */
  public boolean hasMore() {
    return this.pos < this.length;
  } // hasMore

  /**
   * Look at the next character in the stream, but do not advance
   * the stream.
   *
   * Pre: The stream has a next character.
   * Post: Returns that character.  Does not affect the stream.
   *
   * @exception Exception 
   *   if no characters remain.
   */
  public char peek() 
    throws Exception
  {
    if (this.pos >= this.length) {
      throw new Exception("Invalid String Position");
    }
    return this.str.charAt(this.pos);
  } // peek()


  // +-----------+----------------------------------------------------------
  // | Modifiers |
  // +-----------+

  /**
   * Get the next character from the stream and advance the stream.
   *
   * Pre: The stream has a next character.
   * Post: The stream has advanced beyond that character.
   *
   * @exception Exception 
   *   if no characters remain.
   */
  public char next() 
    throws Exception
  {
    char ch = this.peek();
    this.pos++;
    return ch;
  } // next()

} // class StringCharStream;

