The Java Program: Repeat.java

  1 public class Repeat implements CharSequence {
  2 
  3    public final int repetitions;
  4    public final CharSequence base;
  5    private final int len;
  6 
  7    Repeat (int r, CharSequence s) {
  8       assert 1<=r && r<=1000;
  9       repetitions=r;
 10       base=s;
 11       len = r*s.length();  // overflow?
 12       assert 0<=len;
 13    }
 14 
 15    public int length() { return len; }
 16 
 17    public char charAt (int i) {
 18       if (0<=i && i<len) return base.charAt (i % base.length());
 19       throw new IndexOutOfBoundsException ();
 20    }
 21 
 22    public CharSequence subSequence (int start, int end) {
 23       throw new UnsupportedOperationException ();
 24    }
 25 
 26    public String toString () {
 27       return String.format ("%d(%s)", repetitions, base);
 28    }
 29 
 30    public static void main (String [] args) {
 31       CharSequence x;
 32       x = "abc";
 33       System.out.println (new Repeat (2, x));
 34       x = new StringBuilder ("sb");
 35       System.out.println (new Repeat (3, x));
 36       System.out.println (new Repeat (4, "abc"));
 37       System.out.println (new Repeat (5, new StringBuilder ("sb")));
 38       System.out.println (new Repeat (6, new Repeat (7, "cs")));
 39 
 40    }
 41 
 42 }