Reverse.java


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


/*************************************************************************
 *  Compilation:  javac Reverse.java StdIn.java
 *  Execution:    java Reverse
 *  
 *  Reads in real numbers and prints them in reverse order. Uses an
 *  array and repeatedly doubles its size if necessary.
 *
 *  % java Reverse
 *  1.0 2.0 3.0 4.0 5.0 6.0 5.9 5.8 5.7
 *  <Ctrl-d> 
 *  5.7 5.8 5.9 6.0 5.0 4.0 3.0 2.0 1.0 
 *
 *  Windows users: use <Ctrl-z> instead of <Ctrl-d> to signify EOF.
 *
 *************************************************************************/

class Reverse {
   public static void main(String[] args) {
      int N = 0;                          // number of elements in array
      double[] data = new double[1];      // initialze array capacity = 1

      while (!StdIn.isEmpty()) {

         // double the size of the array if necessary
         if (N == data.length) {
            double[] temp = new double[2*N];
            for (int i = 0; i < N; i++) temp[i] = data[i];
            data = temp;
         }

         // read in the next value
         data[N++] = StdIn.readDouble();
      }

      // print it out
      for (int i = N-1; i >= 0; i--)
         System.out.print(data[i] + " ");
      System.out.println();
   }
}


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