Homework J2Due: Friday, 30 September 2005 by 10 a.m. |
In this homework, you will gain more experience using objects while learning about the StringBuffer class. The code should be in a HWJ2 class in a file named HWJ2.java.
For various reasons, Strings are immutable (i.e. they can never be changed once you create them). Consider the following code:
String s = "foo";
s = "bar";
The second line makes s point to a new String "bar" (and the first String is garbage collected away) -- the first string is never modified. Note that you are changing the reference here, not the "foo" object itself. There are no methods in the String class to allow you to change a String object.
There are times when one wants to change a String, and for that Java provides the StringBuffer class. You will need to refer to the Java documentation for the StringBuffer class. A StringBuffer operates much like a String, and has many of the String method that we are familiar with: indexOf(), charAt(), length(), substring(), etc.
The program will have the following steps. Note that in each step the StringBuffer is modified, and those modifications are retained in future steps. Also, the StringBuffer is printed out after each of the steps 5-10.
As the course progresses, we will provide you with less step-by-step instructions for the homeworks -- for example, we don't specify that you need to create a Scanner object to obtain the input (this should be obvious from the fact that you need to get user input), or that you need to print out a legend (which is included in the good programming practices, below).
This homework is not providing a skeleton code file. Your program MUST be in a public class named HWJ2 (note the capitalization), and all your code should be in the main() method.
The good programming practices from HW J1 need to be in this homework as well.
Note that the text in red is what was input by the user. Your program needs to print out similar information, but the format does not have to be the exact same.
This program demonstrates the use of the StringBuffer class. Enter a long string: I think that this course really rules Enter a shorter string within the first string: this course I think that really rules I think that CS101 really rules I think that CS101 really I think that CS101 really rocks I think that CS01 really rocks skcor yllaer 10SC taht kniht I
When you are finished, submit the HWJ2.java file.