Exercises

Included below are short-answer and programming exercises. Answers are provided for those exercises whose exercise number is a hyperlink. Because college faculty use these exercises in their exams, we have provided answers to roughly half of the exercises included here.

10.3 Modify the program in Fig. 10.21 so that the card dealing method deals a five-card poker hand. Then write the following additional methods:

1. Determine if the hand contains a pair.
2. Determine if the hand contains two pairs.
3. Determine if the hand contains three of a kind (e.g., three jacks).
4. Determine if the hand contains four of a kind (e.g., four aces).
5. Determine if the hand contains a flush (i.e., all five cards of the same suit).
6. Determine if the hand contains a straight (i.e., five cards of consecutive face values).
7. Determine if the hand contains a full house (i.e., two cards of one face value and three cards of another face value).

10.4 Use the methods developed in Exercise 10.3 to write a program that deals two five-card poker hands, evaluates each hand, and determines which is the better hand.

10.5 Modify the program developed in Exercise 10.4 so that it can simulate the dealer. The dealer’s five-card hand is dealt "face down" so the player cannot see it. The program should then evaluate the dealer’s hand and, based on the quality of the hand, the dealer should draw one, two, or three more cards to replace the corresponding number of unneeded cards in the original hand. The program should then reevaluate the dealer’s hand. (Caution: This is a difficult problem!)

10.6 Modify the program developed in Exercise 10.5 so that it can handle the dealer’s hand automatically, but the player is allowed to decide which cards of the player’s hand to replace. The program should then evaluate both hands and determine who wins. Now use this new program to play 20 games against the computer. Who wins more games, you or the computer? Have one of your friends play 20 games against the computer. Who wins more games? Based on the results of these games, make appropriate modifications to refine your poker playing program (this, too, is a difficult problem). Play 20 more games. Does your modified program play a better game?

10.7 Write an application that uses String method compareTo to compare two strings input by the user. The program should state whether the first string is less than, equal to or greater than the second.

10.8 Write an application that uses String method regionMatches to compare two strings input by the user. The program should input the number of characters to be compared and the starting index of the comparison. The program should state whether the first string is less than, equal to or greater than the second string. Ignore the case of the characters when performing the comparison.

10.9 Write an application that uses random number generation to create sentences. Use four arrays of strings called article, noun, verb and preposition. Create a sentence by selecting a word at random from each array in the following order: article, noun, verb, preposition, article and noun. As each word is picked, concatenate it to the previous words in the sentence. The words should be separated by spaces. When the final sentence is output, it should start with a capital letter and end with a period. The program should generate 20 sentences and output them to a text area.

The arrays should be filled as follows: the article array should contain the articles "the", "a", "one", "some" and "any"; the noun array should contain the nouns "boy", "girl", "dog", "town" and "car"; the verb array should contain the verbs "drove", "jumped", "ran", "walked" and "skipped"; the preposition array should contain the prepositions "to", "from", "over", "under" and "on".

After the preceding program is written, modify the program to produce a short story consisting of several of these sentences. (How about the possibility of a random term paper writer!)

10.10 (Limericks) A limerick is a humorous five-line verse in which the first and second lines rhyme with the fifth, and the third line rhymes with the fourth. Using techniques similar to those developed in Exercise 10.9, write a Java program that produces random limericks. Polishing this program to produce good limericks is a challenging problem, but the result will be worth the effort!

10.11 (Pig Latin) Write an application that encodes English language phrases into pig Latin. Pig Latin is a form of coded language often used for amusement. Many variations exist in the methods used to form pig Latin phrases. For simplicity, use the following algorithm:

To form a pig Latin phrase from an English language phrase, tokenize the phrase into words with an object of class StringTokenizer. To translate each English word into a pig Latin word, place the first letter of the English word at the end of the word and add the letters "ay." Thus the word "jump" becomes "umpjay," the word "the" becomes "hetay," and the word "computer" becomes "omputercay." Blanks between words remain as blanks. Assume the following: The English phrase consists of words separated by blanks, there are no punctuation marks and all words have two or more letters. Method printLatinWord should display each word. Each token returned from nextToken is passed to method printLatinWord to print the pig Latin word. Enable the user to input the sentence. Keep a running display of all the converted sentences in a text area.

10.12 Write an application that inputs a telephone number as a string in the form (555) 555- 5555. The program should use an object of class StringTokenizer to extract the area code as a token, the first three digits of the phone number as a token and the last four digits of the phone number as a token. The seven digits of the phone number should be concatenated into one string. The program should convert the area code string to int (remember parseInt!) and convert the phone number string to long. Both the area code and the phone number should be printed. Remember that you will have to change delimiter characters during the tokenization process.

10.13 Write an application that inputs a line of text, tokenizes the line with an object of class StringTokenizer and outputs the tokens in reverse order.

10.14 Use the string comparison methods discussed and the techniques for sorting arrays developed in Chapter 7 to write a program that alphabetizes a list of strings. Allow the user to enter the strings in a text field. Display the results in a text area.

10.15 Write an application that inputs text and outputs the text in uppercase and lowercase letters.

10.16 Write an application that inputs several lines of text and a search character, and uses method String method indexOf to determine the number of occurrences of the character in the text.

10.17 Write an application based on the program of Exercise 10.16 that inputs several lines of text and uses String method indexOf to determine the total number of occurrences of each letter of the alphabet in the text. Uppercase and lowercase letters should be counted together. Store the totals for each letter in an array, and print the values in tabular format after the totals have been determined.

10.18 Write an application that reads a series of strings and outputs only those strings beginning with the letter "b." The results should be output to a text area.

10.19 Write an application that reads a series of strings and prints only those strings ending with the letters "ED." The results should be output to a text area.

10.20 Write an application that inputs an integer code for a character and displays the corresponding character. Modify this program so that it generates all possible three-digit codes in the range 000 to 255 and attempts to print the corresponding characters. Display the results in a text area.

10.21 Write your own versions of the String methods for searching strings.

10.22 Write a program that reads a five-letter word from the user and produces all possible three- letter words that can be derived from the letters of the five-letter word. For example, the three-letter words produced from the word "bathe" include the commonly used words "ate", "bat", "bet", "tab", "hat", "the" and "tea."

Special Section: Advanced String Manipulation Exercises

The preceding exercises are keyed to the text and designed to test the reader's understanding of fundamental string manipulation concepts. This section includes a collection of intermediate and advanced string manipulation exercises. The reader should find these problems challenging, yet entertaining. The problems vary considerably in difficulty. Some require an hour or two of program writing and implementation. Others are useful for lab assignments that might require two or three weeks of study and implementation. Some are challenging term projects.

10.23 (Text Analysis) The availability of computers with string manipulation capabilities has resulted in some rather interesting approaches to analyzing the writings of great authors. Much attention has been focused on whether William Shakespeare ever lived. Some scholars believe there is substantial evidence indicating that Christopher Marlowe or other authors actually penned the masterpieces attributed to Shakespeare. Researchers have used computers to find similarities in the writings of these two authors. This exercise examines three methods for analyzing texts with a computer.

1. Write an application that reads several lines of text from the keyboard and prints a table indicating the number of occurrences of each letter of the alphabet in the text. For example, the phrase

To be, or not to be: that is the question:

contains one "a," two "b’s," no "c’s," etc.

2. Write an application that reads several lines of text and prints a table indicating the number of one-letter words, two-letter words, three-letter words, etc. appearing in the text. For example, the phrase

Whether 'tis nobler in the mind to suffer

contains

 Word length Occurrences 1 0 2 2 3 1 4 2 (including 'tis) 5 0 6 2 7 1

3. Write an application that reads several lines of text and prints a table indicating the number of occurrences of each different word in the text. The first version of your program should include the words in the table in the same order in which they appear in the text. For example, the lines

To be, or not to be: that is the question:

Whether 'tis nobler in the mind to suffer

contain the words "to" three times, the word "be" two times, the word "or" once, etc. A more interesting (and useful) printout should then be attempted in which the words are sorted alphabetically.

10.24 (Printing Dates in Various Formats) Dates are printed in several common formats. Two of the more common formats are

04/25/1955 and April 25, 1955

Write an application that reads a date in the first format and prints that date in the second format.

10.25 (Check Protection) Computers are frequently employed in check-writing systems such as payroll applications and accounts payable applications. Many strange stories circulate regarding weekly paychecks being printed (by mistake) for amounts in excess of \$1 million. Incorrect amounts are printed by computerized check-writing systems because of human error and/or machine failure. Systems designers build controls into their systems to prevent such erroneous checks from being issued.

Another serious problem is the intentional alteration of a check amount by someone who intends to cash a check fraudulently. To prevent a dollar amount from being altered, most computerized check-writing systems employ a technique called check protection.

Checks designed for imprinting by computer contain a fixed number of spaces in which the computer may print an amount. Suppose a paycheck contains eight blank spaces in which the computer is supposed to print the amount of a weekly paycheck. If the amount is large, then all eight of those spaces will be filled, for example:

1,230.60 (check amount)
--------
12345678 (position numbers)

On the other hand, if the amount is less than \$1000, then several of the spaces would ordinarily be left blank. For example,

99.87
--------
12345678

contains three blank spaces. If a check is printed with blank spaces, it is easier for someone to alter the amount of the check. To prevent a check from being altered, many check-writing systems insert leading asterisks to protect the amount as follows:

***99.87
--------
12345678

Write an application that inputs a dollar amount to be printed on a check, and then prints the amount in check-protected format with leading asterisks if necessary. Assume that nine spaces are available for printing the amount.

10.26 (Writing the Word Equivalent of a Check Amount) Continuing the discussion of the previous exercise, we reiterate the importance of designing check-writing systems to prevent alteration of check amounts. One common security method requires that the check amount be written both in numbers and "spelled out" in words as well. Even if someone is able to alter the numerical amount of the check, it is extremely difficult to change the amount in words.

Many computerized check-writing systems do not print the amount of the check in words. Perhaps the main reason for this omission is the fact that most high-level languages used in commercial applications do not contain adequate string manipulation features. Another reason is that the logic for writing word equivalents of check amounts is somewhat involved.

Write an application that inputs a numeric check amount and writes the word equivalent of the amount. For example, the amount 112.43 should be written as

ONE HUNDRED TWELVE and 43/100

10.27 (Morse Code) Perhaps the most famous of all coding schemes is the Morse code, developed by Samuel Morse in 1832 for use with the telegraph system. The Morse code assigns a series of dots and dashes to each letter of the alphabet, each digit, and a few special characters (such as period, comma, colon, and semicolon). In sound-oriented systems, the dot represents a short sound and the dash represents a long sound. Other representations of dots and dashes are used with light-oriented systems and signal-flag systems.

Separation between words is indicated by a space, or, quite simply, the absence of a dot or dash. In a sound-oriented system, a space is indicated by a short period of time during which no sound is transmitted. The international version of the Morse code appears in Fig. 10.22.

Fig. 10.22

The letters of the alphabet as expressed in international Morse code.

 Character Code Character Code A .- T - B -... U ..- C -.-. V ...- D -.. W .-- E . X -..- F ..-. Y -.-- G --. Z --.. H .... I .. Digits J .--- 1 .---- K -.- 2 ..--- L .-.. 3 ...-- M -- 4 ....- N -. 5 ..... O --- 6 -.... P .--. 7 --... Q --.- 8 ---.. R .-. 9 ----. S ... 0 -----

Write an application that reads an English language phrase and encodes the phrase into Morse code. Also write a program that reads a phrase in Morse code and converts the phrase into the English language equivalent. Use one blank between each Morse-coded letter and three blanks between each Morse-coded word.

10.28 (A Metric Conversion Program) Write an application that will assist the user with metric conversions. Your program should allow the user to specify the names of the units as strings (i.e., centimeters, liters, grams, etc. for the metric system and inches, quarts, pounds, etc. for the English system) and should respond to simple questions such as

"How many inches are in 2 meters?"
"How many liters are in 10 quarts?"

Your program should recognize invalid conversions. For example, the question

"How many feet in 5 kilograms?"

is not a meaningful question because "feet" is a unit of length while "kilograms" is a unit of mass.

Special Section: Challenging String Manipulation Projects

10.29 (Project: A Spelling Checker) Many popular word processing software packages have built- in spell checkers.

In this project, you are asked to develop your own spell-checker utility. We make suggestions to help get you started. You should then consider adding more capabilities. Use a computerized dictionary (if you have access to one) as a source of words.

Why do we type so many words with incorrect spellings? In some cases, it is because we simply do not know the correct spelling, so we make a "best guess." In some cases, it is because we transpose two letters (e.g., "defualt" instead of "default"). Sometimes we double-type a letter accidentally (e.g., "hanndy" instead of "handy"). Sometimes we type a nearby key instead of the one we intended (e.g., "biryhday" instead of "birthday"). And so on.

Design and implement a spell-checker application in Java. Your program should maintain an array wordList of strings. Enable the user to enter these strings. [Note: In Chapter 17 we introduce file processing. Once you have this capability, you can obtain the words for the spell checker from a computerized dictionary stored in a file.]

Your program should ask a user to enter a word. The program should then look up that word in the wordList array. If the word is present in the array, your program should print "Word is spelled correctly."

If the word is not present in the array, your program should print "word is not spelled correctly." Then your program should try to locate other words in wordList that might be the word the user intended to type. For example, you can try all possible single transpositions of adjacent letters to discover that the word "default" is a direct match to a word in wordList. Of course, this implies that your program will check all other single transpositions, such as "edfault," "dfeault," "deafult," "defalut," and "defautl." When you find a new word that matches one in wordList, print that word in a message, such as "Did you mean "default?"."

Implement other tests, such as replacing each double letter with a single letter and any other tests you can develop to improve the value of your spell checker.

10.30 (Project: A Crossword Puzzle Generator) Most people have worked a crossword puzzle, but few have ever attempted to generate one. Generating a crossword puzzle is suggested here as a string manipulation project requiring substantial sophistication and effort.

There are many issues the programmer must resolve to get even the simplest crossword puzzle generator program working. For example, how does one represent the grid of a crossword puzzle inside the computer? Should one use a series of strings, or should double-subscripted arrays be used?

The programmer needs a source of words (i.e., a computerized dictionary) that can be directly referenced by the program. In what form should these words be stored to facilitate the complex manipulations required by the program?

The really ambitious reader will want to generate the "clues" portion of the puzzle, in which the brief hints for each "across" word and each "down" word are printed for the puzzle worker. Merely printing a version of the blank puzzle itself is not a simple problem.

Included below are answers to approximately half the of the exercises in the Cyber Classroom. We are not able to include answers to every exercise because college faculty use these exercises in their classroom exams.

10.3

```// Exercise 10.3 Solution
// Card shuffling and dealing program
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Poker extends JFrame {
private Card deck[];
private Card hand[];
private int currentCard;
private JButton dealButton, shuffleButton;
private JTextField displayCard;
private JLabel status;
private int numbers[];
private String faces[], suits[], output;

public Poker()
{
super( "Card Dealing Program" );

String f[] = { "Ace", "Deuce", "Three", "Four",
"Five", "Six", "Seven", "Eight",
"Nine", "Ten", "Jack", "Queen",
"King" };
String s[] = { "Hearts", "Diamonds",

faces = f;
suits = s;
numbers = new int[ 13 ];

deck = new Card[ 52 ];
hand = new Card[ 5 ];

currentCard = -1;

for ( int i = 0; i < deck.length; i++ )
deck[ i ] = new Card( faces[ i % 13 ],
suits[ i / 13 ] );

Container c = getContentPane();
c.setLayout( new FlowLayout() );

dealButton = new JButton( "Deal hand" );
new ActionListener() {
public void actionPerformed( ActionEvent e )
{
displayCard.setText( "" );    // clear text area
output = "";

for ( int n = 0; n < hand.length; n++ ) {
Card dealt = dealCard();

if ( dealt != null ) {
hand[ n ] = dealt;
displayCard.setText( displayCard.getText() +
hand[ n ].toString() + "\n" );
}
else {
displayCard.setText(
"NO MORE CARDS TO DEAL" );
status.setText(
"Shuffle cards to continue" );
}
}

totalHand();    // calculates contents of the hand
pair();
threeOfAKind();
fourOfAKind();
straight();
flush();
}
}
);

shuffleButton = new JButton( "Shuffle cards" );
new ActionListener() {
public void actionPerformed( ActionEvent e )
{
displayCard.setText( "SHUFFLING ..." );
shuffle();
displayCard.setText( "DECK IS SHUFFLED" );
}
}
);

displayCard = new JTextField( 20 );
displayCard.setEditable( false );

status = new JLabel();

setSize( 275, 250 );  // set the window size
show();               // show the window
}

public void shuffle()
{
currentCard = -1;

for ( int i = 0; i < deck.length; i++ ) {
int j =  ( int ) ( Math.random() * 52 );
Card temp = deck[ i ];   // swap
deck[ i ] = deck[ j ];   // the
deck[ j ] = temp;        // cards
}

dealButton.setEnabled( true );
}

public Card dealCard()
{
if ( ++currentCard < deck.length )
return deck[ currentCard ];
else {
dealButton.setEnabled( false );
return null;
}
}

private void totalHand()
{
for ( int x = 0; x < faces.length; x++ )
numbers[ x ] = 0;

for ( int h = 0; h < hand.length; h++ )
for ( int f = 0; f < faces.length; f++ )
if ( hand[ h ].getFace().equals( faces[ f ] ) )
++numbers[ f ];
}

public void pair()
{
for ( int k = 0; k < faces.length; k++ )
if ( numbers[ k ] == 2 )
output += ( "Pair of " + faces[ k ] + "'s  " );

status.setText( output );
}

public void threeOfAKind()
{
for ( int k = 0; k < faces.length; k++ )
if ( numbers[ k ] == 3 ) {
output += ( "Three " + faces[ k ] + "'s" );
break;
}

status.setText( output );
}

public void fourOfAKind()
{
for ( int k = 0; k < faces.length; k++ )
if ( numbers[ k ] == 4 )
output += ( "Four " + faces[ k ] + "'s" );

status.setText( output );
}

public void flush()
{
String theSuit = hand[ 0 ].getSuit();

for ( int s = 1; s < hand.length; s++ )
if ( hand[ s ].getSuit().compareTo( theSuit ) != 0 )
return;   // not a flush

output += ( "flush in " + theSuit );
status.setText( output );
}

public void straight()
{
int locations[] = new int[ 5 ], z = 0;

for ( int y = 0; y < numbers.length; y++ )
if ( numbers[ y ] == 1 )
locations[ z++ ] = y;

bubbleSort( locations );

int faceValue = locations[ 0 ];

for ( int m = 1; m < locations.length; m++ ) {

if ( faceValue != locations[ m ] - 1 )
return;   // not a straight
else
faceValue = locations[ m ];
}

output += "straight ";
status.setText( output );
}

private void bubbleSort( int values[] )
{
for ( int pass = 1; pass < values.length; pass++ )
for ( int comp = 0; comp < values.length - 1; comp++ )
if ( values[ comp ] > values[ comp + 1 ] ) {
int temp = values[ comp ];
values[ comp ] = values[ comp + 1 ];
values[ comp + 1 ] = values[ comp ];
}
}

public static void main( String args[] )
{
Poker app = new Poker();

public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
}
}

class Card {
private String face;
private String suit;

public Card( String f, String s )
{
face = f;
suit = s;
}

protected String getSuit() { return suit; }
protected String getFace() { return face; }
public String toString() { return face + " of " + suit; }
}

/**************************************************************************
* (C) Copyright 1999 by Deitel & Associates, Inc. and Prentice Hall.     *
*                                                                        *
* DISCLAIMER: The authors and publisher of this book have used their     *
* best efforts in preparing the book. These efforts include the          *
* development, research, and testing of the theories and programs        *
* to determine their effectiveness. The authors and publisher make       *
* no warranty of any kind, expressed or implied, with regard to these    *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or       *
* consequential damages in connection with, or arising out of, the       *
* furnishing, performance, or use of these programs.                     *
*************************************************************************/```

10.7

```// Exercise 10.7 Solution
// CompareStrings.java
// Program compares two strings
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class CompareStrings extends JFrame {
private JLabel prompt1, prompt2;
private JTextField input1, input2, output;

public CompareStrings()
{
super( "Compare Strings" );

prompt1 = new JLabel( "Enter first string:" );
prompt2 = new JLabel( "Enter second string:" );
input1 = new JTextField( 20 );
input2 = new JTextField( 20 );
output = new JTextField( 30 );
output.setEditable( false );

new ActionListener() {
public void actionPerformed( ActionEvent e )
{
String first = input1.getText();
String second = input2.getText();
int value = first.compareTo( second );

if ( value == 0 )
output.setText( first + " == " + second );
else if ( value > 0 )
output.setText( first + " > " + second );
else
output.setText( first + " < " + second );
}
}
);
Container c = getContentPane();
c.setLayout( new FlowLayout() );

setSize( 375, 150 );
show();
}

public static void main( String args[] )
{
CompareStrings app = new CompareStrings();

public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
}
}```

10.11

```// Exercise 10.11 Solution
// PigLatin.java
// Program translates English to pig Latin
import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;

public class PigLatin extends JFrame {
private JLabel prompt;
private JTextField input;
private JTextArea output;
private int count;

public PigLatin()
{
super( "Pig Latin Generator" );
prompt = new JLabel( "Enter English phrase:" );
input = new JTextField( 30 );
new ActionListener() {
public void actionPerformed( ActionEvent e )
{
String s = e.getActionCommand().toString();
StringTokenizer tokens = new StringTokenizer( s );

count = tokens.countTokens();

while ( tokens.hasMoreTokens() ) {
count--;
printLatinWord( tokens.nextToken() );
}
}
}
);

output = new JTextArea( 10, 30 );
output.setEditable( false );

Container c = getContentPane();
c.setLayout( new FlowLayout() );

setSize( 500, 150 );
show();
}

private void printLatinWord( String token )
{
char letters[] = token.toCharArray();
StringBuffer schweinLatein = new StringBuffer();

schweinLatein.append( letters, 1, letters.length - 1 ) ;
schweinLatein.append( Character.toLowerCase( letters[ 0 ] ) );
schweinLatein.append( "ay" );

output.append( schweinLatein.toString() + " " );

if ( count == 0 )
output.append( "\n" );
}

public static void main( String args[] )
{
PigLatin app = new PigLatin();

public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
}
}```

10.14

```// Exercise 8.14 Solution
// SortThem.java
// Program sorts strings
import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;

public class SortThem extends JFrame {
private JTextField input;
private JLabel prompt;
private JTextArea output;
private JScrollPane scroller;

public SortThem()
{
super( "String Sorter" );
input = new JTextField( 10 );
new ActionListener() {
public void actionPerformed( ActionEvent e )
{
String newString = input.getText();
String oldString = output.getText();
StringTokenizer t = new StringTokenizer( oldString, "\n" );
int number = t.countTokens(), c = 0;
String tokens[] = new String[ number + 1 ];

input.setText( "" );
output.setText( "" );

while ( t.hasMoreTokens() && c < number )
tokens[ c++ ] = t.nextToken();

tokens[ c ] = newString;
bubbleSort( tokens );

for ( int k = 0; k < tokens.length; k++ )
output.append( tokens[ k ] + "\n" );
}
}
);
output = new JTextArea( 10, 10 );
scroller = new JScrollPane( output );
prompt = new JLabel( "Enter a String:" );

Container c = getContentPane();
c.setLayout( new FlowLayout() );

setSize( 200, 230 );
show();
}

private void bubbleSort( String s[] )
{
for ( int pass = 1; pass < s.length; pass++ )
for ( int c = 0; c < s.length - pass; c++ )
if ( s[ c ].compareTo( s[ c + 1 ] ) > 0 ) {
String temp = s[ c ];
s[ c ] = s[ c + 1 ];
s[ c + 1 ] = temp;
}
}

public static void main( String args[] )
{
SortThem app = new SortThem();

public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
}
}```

10.16

```// Exercise 10.16 Solution
// Index.java
// Program outputs the number of times a
// search character was found
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Index extends JFrame {
private JTextField inputKey;
private JLabel promptKey;
private JTextArea input;
private int count;

public Index()
{
super( "Character Finder" );
inputKey = new JTextField( 4 );
new ActionListener() {
public void actionPerformed( ActionEvent e )
{
count = 0;
String key = e.getActionCommand().toString();
String s = input.getText();
int last = -2, current = 0;

for ( int j = -1; j < s.length();  ) {
current = s.indexOf( key.charAt( 0 ), ++j );

if (  current != -1 && current != last ) {
last = current;
count++;
}
}

JOptionPane.showMessageDialog(
null, "Number of " + key.charAt( 0 ) +
"'s: " + count, "Results",
JOptionPane.INFORMATION_MESSAGE );
}
}
);

promptKey = new JLabel( "Enter a character:" );
input = new JTextArea( 4, 20 );

Container c = getContentPane();
c.setLayout( new FlowLayout() );

setSize( 375, 150 );
show();
}

public static void main( String args[] )
{
Index app = new Index();

public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
}
}```

10.18

```// Exercise 10.18 Solution
// FirstB.java
// Program outputs strings that begin with "b"
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class FirstB extends JFrame {
private JTextField input;
private JLabel prompt;
private JTextArea display;

public FirstB()
{
super( "FirstB" );
input = new JTextField( 20 );
new ActionListener() {
public void actionPerformed( ActionEvent e )
{
String s = e.getActionCommand().toString();

if ( s.startsWith( "b" ) )
display.append( s + "\n" );

input.setText( "" );
}
}
);

prompt = new JLabel( "Enter a string:" );
display = new JTextArea( 4, 20 );
display.setEditable( false );

Container c = getContentPane();
c.setLayout( new FlowLayout() );

setSize( 375, 150 );
show();
}

public static void main( String args[] )
{
FirstB app = new FirstB();