public class ReverseLine
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
12: (
13: "\nThis program reads a sentence and "
14: + "then writes it out in reverse order."
15: );
17: System.out.println
18: (
19: "Enter a sentence on the following line "
20: + "and press Enter:"
21: );
22: readRestOfCharsAndWriteInReverse();
23: //readRestOfCharsAndWriteInReverse2();
24: System.out.println();
25: }
27: /**
28: Read a string of characters from an input line and then write
29: those characters out in reverse.
30: <p>Pre:<p>The standard input stream is empty.
31: <p>Post: All characters entered by the user, up to the first newline
32: character, have been read in and written out in reverse order.
33: */
34: public static void readRestOfCharsAndWriteInReverse() throws IOException
35: {
36: char ch = (char)System.in.read();
37: if (ch == '\n')
38: ; //Stop. That is, do nothing, since you're finished.
39: else
40: {
41: readRestOfCharsAndWriteInReverse();
42: System.out.print(ch);
43: }
44: }
46: /**
47: Read a string of characters from an input line and then write
48: those characters out in reverse.
49: <p>Pre:<p>The standard input stream is empty.
50: <p>Post: All characters entered by the user, up to the first newline
51: character, have been read in and written out in reverse order.
52: */
53: public static void readRestOfCharsAndWriteInReverse2() throws IOException
54: {
55: char ch = (char)System.in.read();
56: if (ch != '\n')
57: {
58: readRestOfCharsAndWriteInReverse2();
59: System.out.print(ch);
60: }
61: }
62: }