LAB 36 – Creating and Modifying Text (part 1)
Lab Exercises
Topics
n To manipulate structured text, such as a delimited string.
n To manipulate strings
n To use the swing class JOptionPane
Exercises
12.2 Strings: Character Sequences
i) Open a new file in Dr. Java and type in the following program:
//********************************************************************
// PalindromeTester.java Author: Lewis/Loftus
//
// Demonstrates the use of nested while loops.
//********************************************************************
import java.util.Scanner;
public class PalindromeTester
{
//-----------------------------------------------------------------
// Tests strings to see if they are palindromes.
//-----------------------------------------------------------------
public static void main (String[] args)
{
String str, another = "y";
int left, right;
Scanner scan = new Scanner (System.in);
while (another.equalsIgnoreCase("y")) // allows y or Y
{
System.out.println ("Enter a potential palindrome:");
str = scan.nextLine();
left = 0;
right = str.length() - 1;
while (str.charAt(left) == str.charAt(right) && left < right)
{
left++;
right--;
}
System.out.println();
if (left < right)
System.out.println ("That string is NOT a palindrome.");
else
System.out.println ("That string IS a palindrome.");
System.out.println();
System.out.print ("Test another palindrome (y/n)? ");
another = scan.nextLine();
}
}
}
ii) Test your program (radar; able was I ere I saw elba; a man, a plan, a canal, Panama).
iii) Modify the main method by
a. Add import javax.swing.JOptionPane;
b. Change the while loop to a do-while using a JOptionPane
i. Declare an integer variable again to hold the result of the pop-up
ii. Replace System.out.print ("Test another palindrome (y/n)? ");
with again = JOptionPane.showConfirmDialog (null, "Do Another?");
iii. Replace the condition in the while with again == JOptionPane.YES_OPTION
c. Replace the input and prompt:
i. Replace System.out.println ("Enter a potential palindrome:");
str = scan.nextLine();
with str = JOptionPane.showInputDialog ("Enter a potential palindrome:");
d. Replace the results:
i. Replace the two remaining System.out.println with
JOptionPane.showMessageDialog (null, "That string is NOT a palindrome.");
QUESTIONS:
Submit the PalindromeTester.java files through the DropBox in WebCT.