|
|
`Reverse1' example program: reverse a string; demonstrates string handling
Reverse1.java
// CountSpace1.java
// A program that reverses a text string.
// Note that there are many ways to do this; this program only demonstrates one way
// Kevin Boone, August 1999
import java.applet.Applet;
import java.awt.*;
public class Reverse1 extends Applet
{
public void paint (Graphics g)
{
// 'text' is the String to be reversed
String text = "Fred Bloggs";
// Start by creating a character array of exactly the same length as `text'.
// This is because Java allows individual elements of an array to be changed,
// but not individual characters of a String
char reversedText[] = new char[text.length()];
// Now move each character in `text' to the right place in `reversedText'
for (int i = 0; i < text.length(); i++)
reversedText[i] = text.charAt(text.length() - i - 1);
// `reversedText' is an array; Java will not allow us to use `drawString' to
// print an array (it can only print Strings). So we create a new String
// that has exactly the same text as `reversedtext'
String reversedTextString = new String(reversedText);
// Now print the String
g.drawString (reversedTextString, 20, 40);
}
}
|