Source of ReverseLine.java


  1: //ReverseLine.java
  2: //Reads in a line of input and then writes out
  3: //the line with all characters in reverse order.

  5: import java.io.IOException;

  7: public class ReverseLine
  8: {
  9:     public static void main(String[] args) throws IOException
 10:     {
 11:         System.out.println("\nThis program reads a sentence and "
 12:             + "then writes it out in reverse order.");

 14:         System.out.println("Enter a sentence on the following line "
 15:             + "and press Enter:");
 16:         readRestOfCharsAndWriteInReverse();
 17:         //readRestOfCharsAndWriteInReverse2();
 18:         System.out.println();
 19:     }

 21:     /**
 22:     Read a string of characters from an input line and then write
 23:     those characters out in reverse.
 24:     <p>Pre:<p>The standard input stream is empty.
 25:     <p>Post: All characters entered by the user, up to the first newline
 26:     character, have been read in and written out in reverse order.
 27:     */
 28:     public static void readRestOfCharsAndWriteInReverse() throws IOException
 29:     {
 30:         char ch = (char)System.in.read();
 31:         if (ch == '\n')
 32:             ; //Stop. That is, do nothing, since you're finished.
 33:         else
 34:         {
 35:             readRestOfCharsAndWriteInReverse();
 36:             System.out.print(ch);
 37:         }
 38:     }

 40:     /**
 41:     Read a string of characters from an input line and then write
 42:     those characters out in reverse.
 43:     <p>Pre:<p>The standard input stream is empty.
 44:     <p>Post: All characters entered by the user, up to the first newline
 45:     character, have been read in and written out in reverse order.
 46:     */
 47:     public static void readRestOfCharsAndWriteInReverse2() throws IOException
 48:     {
 49:         char ch = (char)System.in.read();
 50:         if (ch != '\n')
 51:         {
 52:             readRestOfCharsAndWriteInReverse2();
 53:             System.out.print(ch);
 54:         }
 55:     }
 56: }