/* COSC 304 section 2 LUKE BURGESS luke_burgess@hotmail.com @00205854 Nov 2 2000 */ // Lab task: Exercises 10.14 and 10.16, page 507 from "Java How To Program", Deitel & Deitel // Applet that alphabetizes a series of strings entered by the user, and determines number // of occurences of a particular character. import javax.swing.*; import java.util.*; import java.awt.*; import java.awt.event.*; public class Exercises1416p507 extends JApplet implements ActionListener { private JLabel stringLabel, charLabel, outputLabel; private JTextField stringField, charField; private JTextArea output; private int charCount; public void init() { Container c = getContentPane(); c.setLayout (new FlowLayout()); c.setBackground(Color.decode("#ccccff")); stringLabel = new JLabel ("Enter a String: "); stringField = new JTextField (10); stringField.addActionListener (this); c.add (stringLabel); c.add (stringField); charLabel = new JLabel ("Enter Character: "); charField = new JTextField (9); charField.addActionListener (this); c.add (charLabel); c.add (charField); outputLabel = new JLabel ("Sorted Strings:"); output = new JTextArea (10, 10); c.add (outputLabel); c.add (output); } // init() public void actionPerformed (ActionEvent e) { if (e.getSource() == stringField) { // Exercise 10.14 String newString = stringField.getText(); String oldString = output.getText(); StringTokenizer t = new StringTokenizer (oldString, "\n"); int count = 0; int number = t.countTokens(); String tokens[] = new String[ number + 1 ]; stringField.setText (""); output.setText (""); while (t.hasMoreTokens() && count < number) tokens[ count++ ] = t.nextToken(); tokens[ count ] = newString; bubbleSort (tokens); for (int k = 0; k < tokens.length; k++) output.append (tokens[ k ] + "\n"); } else if (e.getSource() == charField) { // Exercise 10.16 charCount = 0; String key = e.getActionCommand().toString(); String s = output.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; charCount++; } } JOptionPane.showMessageDialog ( null, "Number of " + key.charAt(0) + "'s = " + charCount, "Results", JOptionPane.INFORMATION_MESSAGE); } } // actionPerformed() private void bubbleSort (String b[]) { for (int pass = 1; pass < b.length; pass++) for (int i = 0; i < b.length - pass; i++) if (b[ i ].compareTo (b[ i + 1 ]) > 0) { String hold = b[ i ]; b[ i ] = b[ i + 1 ]; b[ i + 1 ] = hold; } } // bubbleSort() } // class Exercises1416p507