Java Basics  «Prev 

Implementing Java Interfaces - Exercise

In this exercise, you must implement an interface defined in the java.util package, called Enumeration. Refer to the API documentation for a description of this interface.

Create a class

You will see that the Enumeration interface defines two methods: hasMoreElements() and nextElement(). Your mission is to create a class called StringEnumeration that implements this interface and provides behavior for these two methods.
In particular, once you create your new StringEnumeration class and add it to the following file, you will have a complete, working application in which the StringEnumeration class is used to generate a series of Character objects corresponding to the characters of a String object. Here's the code for the class SuperString that contains a main() method that makes use of the StringEnumeration class.

classSuperString {
  public static void main(String[] args) {
    StringEnumeration se = new StringEnumeration("Hello, World!");
    while (se.hasMoreElements())
      System.out.println(se.nextElement());
    }
 }

Class specifics

Your StringEnumeration class should do the following:
  1. Define an instance variable s for a String object and an instance variable n for an integer. The instance variable n should be initialized to 0 and will be used as an index into the String object.
  2. Supply a constructor that takes a String object and assigns it to the String instance variable.
  3. Implement the method hasMoreElements(). This method should return true if the length of s is greater than n.
  4. Implement the method nextElement(). This method should return an instance of the Character class that is created using the character at the index n of s. To obtain the character at the index n of s you can use the charAt(int) method of the String class. The nextElement() method should also increment the instance variable n.

When your solution is working, the following will appear in the standard output:
H
e
l
l
o
,

W
o
r
l
d
!

Copy and paste your code for your StringEnumeration class into the text area below.