/* ReverseText written by Keith Fenske Sunday, 12 May 2002 Copyright (c) 2002 by Keith Fenske. All rights reserved. This Java program reverses a string using only the String.charAt(), String.equals(), and String.length() methods. Input is read from the user in a loop until the input is the string "*" (only an asterisk character). */ import cs1.Keyboard; // import Lewis/Loftus keyboard class // http://duke.csc.villanova.edu/jss/keyboard.html public class ReverseText { public static void main(String[] args) { String user; // user's input string do { System.out.println("\nPlease type a string (or * to quit):"); user = Keyboard.readString(); System.out.println("\noriginal string: \"" + user + "\""); System.out.println("reversed string: \"" + reverse(user) + "\""); System.out.println("original string: \"" + user + "\""); } while (! user.equals("*")); } // end of main() /* reverse() method This method takes one string parameter and returns a string result. The characters in the result string are in reverse (opposite) order compared to the characters in the parameter string. Note that the parameter string can have zero or more characters. We start by setting the result string to an empty string. Then we append one character at a time from the parameter string. */ static String reverse(String input) { int i; // index variable in "for" loop int length; // length of parameter string String result; // our result string result = ""; // start with empty result string length = input.length(); // get number of characters for (i = (length-1); i >= 0; i --) // backwards order result = result + input.charAt(i); // append one character to result return result; // finished } // end of reverse() } // end of class