Last Updated: 2017-10-14 Sat 13:00

CSCI 1103 Lab06: Strings, Methods, and Palindromes

CODE DISTRIBUTION: lab06-code.zip

  • Download the code distribution every lab
  • See further setup instructions below

CHANGELOG:

1 Rationale

Strings are a central data type in Java and most other programming languages as they represent text information which carries great meaning or humans. There are many things one can do with strings but principle among them is to recognize that operations on textural information are really operations on an arrays of individual characters so that all knowledge of how array processing works transfers directly to String variables though the names may be different. This lab involves a simple problem of identifying symmetric words known as palindromes.

All sensible programming languages have the means to specify an algorithm that will run when certain information is provided. These are referred to by many names, functions, subroutines, methods, parameterized code, etc. Java refers to them as methods and this lab covers basic static method definition and use.

Associated Reading

  • Eck Chapter 2.3.3 discusses the String class briefly and outlines some of its useful methods such as length() and charAt() though few details are given. Transferring awareness of these funcionalities and knowledge about arrays to Strings will help to solve Problem 1.
  • Ech Chapter 4 introduces and discusses the use of Subroutines, known as methods in Java. Reading this material will acquaint one with how Problem 2 decomposes a problem into steps that are solved via methods.

2 Download Lab Code and Setup

As in Lab01, download the code pack linked at the top of the page. Unzip this which will create a folder and create your files in that folder.

File State Notes
PARTNERS.txt Edit Fill in your name and the name of your partner in this text file
TextIO.java Provided Allows easy input calls like TextIO.getInt()
KTests.java Testing Utility routines for all tests
junit-1103.jar Testing For testing, don't try to edit this one
PalindromeTests.java Testing Tests for problem 1
PalMethodsTests.java Testing Tests for problem 2
Palindrome.java Create Create this file for Problem 1
PalMethods.java Modify Modify this file for Problem 2

3 Problem 1: Palindrome (TESTED)

A palindrome is a word a symmetric word: it has the same sequence of letters read forwards and backwards. It is a classic exercise in string processing to determine whether a string is a palindrome. Example palindromes are

  • racecar
  • tenet
  • levels
  • rotator

There are not many single word palindromes which has led creative linguists to extend the definition to allow sentences (notably, A man, a plan, a canal - Panama!) which ignore spaces. We will focus only on single word palindromes in this problem.

The goal of the problem is to develop a program which prompts the user for a word, prints back the word in reverse character order, and identifies it as a palindrome or not.

3.1 Basic Approach

The central algorithm involved in palindrome detection is identical to the algorithm for detecting symmetric integer sequences: in a loop, compare 0th and last elements, then next and next to last, and so forth. If any differences are detected, the word is not a palindrome while no differences means the word is a palindrome. Review the basic approach to this problem if you have forgotten as it will prove useful here.

Below are some of the adaptations required for Java's String data type.

  • Use TextIO.getWord() to get a single input String from the user. There is no need to prompt for length as the entire word will be read and provided as a String.
  • Strings are sequences of characters much like arrays but different mechanisms must be used to process them.
    • Use str.length() to determine the size of the String; note the parentheses at the end as string size is a method invocation rather than a field. This difference will be discussed at length later on in the course.
    • Use str.charAt(i) to get individual character elements from the string instead of array syntax with square braces. str[i] will NOT WORK for strings.
  • To print a string in reverse order, use a loop starting at its str.length()-1 character and decreases down to character 0. Repeatedly call str.charAt(i) to get the single character at the given position and print it to the screen
  • Testing for symmetry is identical to the symmetric sequence problem with the use of charAt(i) to reference elements of the string.

3.2 Demos

> javac Palindrome.java 
> java Palindrome
Enter a word: 
professor
The word backwards is: rosseforp
NOT a palindrome
> java Palindrome
Enter a word: 
racecar
The word backwards is: racecar
IS a palindrome
> java Palindrome
Enter a word: 
level
The word backwards is: level
IS a palindrome
> java Palindrome
Enter a word: 
computer
The word backwards is: retupmoc
NOT a palindrome
> java Palindrome
Enter a word: 
tenet
The word backwards is: tenet
IS a palindrome
> java Palindrome
Enter a word: 
amanaplanacanalpanama
The word backwards is: amanaplanacanalpanama
IS a palindrome
>

4 Problem 2: PalMethods (TESTED)

As problems become more complex, it becomes necessary to divide them into sub-problems which are easier to solve. In computing this is done in a many ways but among the most important is via functions, subroutines, or methods. These are units of code that take some input parameters, run an algorithm, and then potentially return an answer.

To practice this technique, this problem will revisit the functionality of Problem 1 and break some important pieces into Java methods which are then used in the main() method to accomplish the overall goal.

4.1 Structure of PalMethods.java

Unlike previous programs, the PalMethods.java file will have a main() method and also two additional methods. The overall structure of the file is provided in and will look similar to the outline below. Comments for what each part of PalMethods.java does appear below the method declaration.

public class PalMethods{
// Class which contains methods to
// - Print words in reverse
// - Check if a word is a palindrome
// - Main method using the two methods above

  public static void printBackwards(String word);
  // Print the parameter word on the screen in reverse character
  // order.  Use a loop and calls to either printf() or print() to put
  // characters on the screen. If using printf(), make use of the the
  // "%c" format specifier which substitues in a single
  // character. Print a newline at the end of printing the word.

  public static boolean isPalindrome(String word);
  // Check the parameter word for whether it is a palindrome or
  // not. Uses a loop to compare 0th and last chars, 1th and next to
  // last chars, and so forth. If word is a palindrome, return
  // true. If not, return false. This method DOES NOT print anything
  // to the screen, only returns a true/false value.

  public static void main(String args[]);
  // Prompt the user for a word, print it in reverse, and the check
  // whether it is a palindrome. Print messages corresponding to this.

}

Note that there are 3 total methods:

  • printBackWards()
  • isPalindrome()
  • main()

Each of these will be discussed in the following sections.

4.2 printBackwards()

public class PalMethods{
  public static void printBackwards(String word){ ... }
  ...
}

This method takes a parameter called word and does not return anything as it has a void return type. printBackwards() should print word on the screen in reverse character order. The same loop as was used to do this in Problem 1 can be used here. Importantly, the method should NOT use TextIO to get a word. Instead, the word is given to the method as a parameter named word by some code elsewhere as demonstrated below.

In DrJava, one can manually experiment with printBackwards() in the Interactions Pane by typing the following.

Welcome to DrJava
> String s = "computer";
> PalMethods.printBackwards(s);
retupmoc
> s = "racecar";
> PalMethods.printBackwards(s);
racecar
> PalMethods.printBackwards("hello");
olleh
> PalMethods.printBackwards("madam");
madam
>

Note the use of PalMethods to name the class in which the method lives. This is required as the interactions pane is outside of the PalMethods class. It is similar to Math.sqrt() being required to calculate a square root as that method lives in the Math class and System.out to get println() to work.

The full name PalMethods.printBackwards() is necessary in the interactive pane but not within the PalMethods.java file itself. For example, in the main() method of PalMethods, one could do the following.

public class PalMethods{
  public static void printBackwards(String word){
    ...
  }

  public static void main(String args[]){

    ...;

    printBackwards(inputWord);    // Since printBackwards() is in the same class as main
                                  // don't need to use full name PalMethods.printBackwards()
    ...;
  }
}

The printBackwards() method is tested individually in the test file PalMethodsTests.java so must be present and work independently of the other parts of the program.

4.3 isPalindrome()

public class PalMethods{
  public static boolean isPalindrome(String word){ ... }
  ...
}

This method takes a parameter word and determines if it is a palindrome or not. Importantly it does not print anything to the screen. Thus, no println() or printf() calls should appear in its definition.

Instead, isPalindrome() returns a boolean value to whatever invoked it. The method will use a loop to determine whether a word is or is not a palindrome. Once this true/false value has been determined, issue a return statement as in

return true;

// OR

return false;

// OR if the answer is in a variable

boolean answer = ...;
...
return answer;

A return statement immediately ends the method and gives back the answer to whoever called the method. If the method has a return type of boolean, it must return a boolean value.

Returning a boolean allows isPalindrome() to be used anyplace one would expect a boolean value such as:

// this code might appear in the main() method for PalMethods

boolean b = isPalindrome("racecar");      // b will get value true
if(b){
  System.out.println("IS a palindrome");
}

if(isPalindrome("computer")){             // computer not a palindrome: false
  System.out.println("IS a palindrome");
}
else{
  System.out.println("NOT a palindrome"); // will print this
}

One can directly test isPalindrome() in DrJava's Interactions Pane by typing the following.

Welcome to DrJava
> boolean isp = PalMethods.isPalindrome("racecar");  // isp gets value true
> isp                                                // show value of isp
true
> isp = PalMethods.isPalindrome("computer");         // not a palindrome: assigns isp false
> isp                                                // show value of isp
false
> PalMethods.isPalindrome("professor")               // no semicolon: show return value on screen
false
> PalMethods.isPalindrome("tenet")                   // no semicolon: show return value on screen
true

4.4 main()

The main() method for PalMethods.java will have identical behavior to Problem 1 but will make use of the printBackwards() and isPalindrome() methods. This will make main() a bit shorter following the below steps.

  • Prompt for an input word and store it in a variable
  • Print the word in reverse character order using printBackwards()
  • Use the isPalindrome() method to determine whether the word is a palindrome or not and print an appropriate message.
  • There should not be any loops in main() as the two methods will have the loops.

4.5 Demos of PalMethods.main()

> javac PalMethods.java 
> java PalMethods
Enter a word: 
professor
The word backwards is: rosseforp
NOT a palindrome
> java PalMethods
Enter a word: 
racecar
The word backwards is: racecar
IS a palindrome
> java PalMethods
Enter a word: 
level
The word backwards is: level
IS a palindrome
> java PalMethods
Enter a word: 
computer
The word backwards is: retupmoc
NOT a palindrome
> java PalMethods
Enter a word: 
tenet
The word backwards is: tenet
IS a palindrome
> java PalMethods
Enter a word: 
amanaplanacanalpanama
The word backwards is: amanaplanacanalpanama
IS a palindrome
>

5 Getting Credit for this Lab

5.1 Demonstrate your code to Lab Staff (40%)

You should feel free at any time to get help from lab staff as you get stuck on the exercises.

By the end of the lab, make sure to demonstrate your code to a staff member. This will ensure that you receive full credit on the lab. Staff might ask you to

  • Change what is printed
  • Compile and run on the command line
  • Run tests in DrJava or on the command line
  • Show how to zip the folder with your programs in it

Be ready to do any or all of these.

5.2 Zip and Submit (60%)

Ensure that file PARTNERS.txt has your name and the name of your partner in it. This fill is located with the other Java files for the lab and can be edited with DrJava.

Once your are confident your code is working, you are ready to submit. Ensure your folder has all of the required files. Create a zip archive of your lab folder and submit it to blackboard.

On Canvas:

  • Click on the Assignments section
  • Click on the appropriate link for this lab
  • Scroll down to "Attach a File"
  • Click "Browse My Computer"
  • Select you Zip file and press OK

Author: Chris Kauffman (kauffman@cs.gmu.edu)
Date: 2017-10-14 Sat 13:00