RunLengthEncoder.java


Below is the syntax highlighted version of RunLengthEncoder.java from §1.5 Input and Output.


/*************************************************************************
 *  Compilation:  javac RunLengthEncoder.java
 *  Execution:    java RunLengthEncoder < data.txt
 *  Dependencies: StdIn.java
 *  
 *  Reads in a sequence of 0's and 1's and encodes using RLE.
 * 
 *  % java RunLengthEncoder
 *  00001111000011111
 *  4 4 4 5
 *
 *************************************************************************/

public class RunLengthEncoder { 

   public static void main(String[] args) { 
      char last = '0';
      int count = 0;

      while (!StdIn.isEmpty()) {
         char c = StdIn.readChar();

         // new line
         if (c == '\n') {
            System.out.println("" + count);
            count = 0;
            last = '0';
         }

         // validate input
         else if ((c != '0') && (c != '1'))
            throw new RuntimeException("Invalid input");

         // repeated character
         else if (c == last) count++;

         // changes from 0 to 1 or from 1 to 0
         else {
            System.out.print(count + " ");
            count = 1;
            last = c;
         }
      }
      System.out.println(count);
   }
}


Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.
Last updated: Wed Feb 9 09:02:07 EST 2011.