The goal of this assignment is to practice writing with arrays. This part is a warm-up so you can come to lab-day on Friday having already thought about arrays and perhaps having some questions.
As in previous assignments, move into your cs241
directory.
Make a directory for this assignment, and change into it.
> cd cs241 > mkdir assign7 > cd assign7
Like last time, I am giving you partially-written files to start with. For this part, copy one file from the public directory:
> cp /homeemp/tvandrun/pub/241/ManyPalindromes.java .
charAt
Notice that the method palindromeIterative
differs from what you did last time in that it doesn't call
text.charAt()
. Instead, it calls a method defined
locally, called homemadeCharAt
.
Write the body of that method.
It should work exactly like charAt
and it
should use the string method (some string).toCharArray()
which will return an array of characters that is equivalent to the
string. For example, in the code
String str = "hello"; char[] array = str.toCharArray();
array
is set to {'h', 'e', 'l', 'l', 'o'}
.
Don't make this harder than it needs to be--- this can be done in one line!
Compile and test. The easiest way to make sure that it works is to
explicitly call palindromeIterative
on some strings in the main method,
like
System.out.println(palindromeIterative("wheaton")); System.out.println(palindromeIterative("racecar"));
Remember that we've noticed that the main method has a parameter--- it's an array of Strings. The Java Virtual Machine creates that array based on what the user types at the command line when starting your program. For example, if someone were to type
> java YourProgram hello my name is someone
then the main method in the program YourProgram would be passed an array of the five strings that follow the name of the program:
{"hello", "my", "name", "is", "someone"}
This time, instead of prompting the user for palindromes,
we'll use the strings on the command line and test them.
So, in your main method, delete all the testing code you
had from the earlier section.
Then write a loop that iterates through
the elements of args
.
For each one, print it and display whether or not it is a palindrome.
A sample run might look like
> java ManyPalindromes wheaton level radar computer wheaton false level true radar true computer false
Compile and test.
You'll hand this in later with the rest of this assignment.