EXAMPLES FOR DAY 7 ******************* // Project Names1 // Class Word // First solution to Problem 10 of Summer I 2000 midterm. import java.io.*; public class Word { public static void main(String[] args) throws IOException { NameLocator x = new NameLocator(); } } ******************* // Project Names1 // Class NameLocator // First solution to Problem 10 of Summer I 2000 midterm. import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; public class NameLocator extends JFrame { JTextField name, result; JLabel nameLabel, resultLabel; JButton search; JPanel panel; String[] names; int numbNames; public NameLocator() throws IOException { super("Search"); setSize(150, 160); name = new JTextField(10); result = new JTextField(10); nameLabel = new JLabel("Name to Find"); resultLabel = new JLabel("Result"); search = new JButton("Search for Name"); panel = new JPanel(); names = new String[100]; panel.add(name); panel.add(nameLabel); panel.add(result); panel.add(resultLabel); panel.add(search); setContentPane(panel); show(); MyListener listener = new MyListener(); search.addActionListener(listener); FileReader fr = new FileReader("c:\\names.txt"); BufferedReader in = new BufferedReader(fr); int i = 0; String line; while((line = in.readLine()) != null) names[i++] = line; numbNames = i; } private class MyListener implements ActionListener { public void actionPerformed(ActionEvent e) { int i; for(i = 0; i < numbNames; i++) if (name.getText().equals(names[i])) { result.setText("Name found"); return; } result.setText("Name not found."); } } } ******************* // Project Names2 // Class Main // Second solution to Problem 10 of Summer I 2000 midterm. import java.io.*; public class Main { public static void main(String[] args) { NameLocator x = new NameLocator(); } } ******************* // Project Names2 // Class NameLocator // Second solution to Problem 10 of Summer I 2000 midterm. import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; public class NameLocator extends JFrame { JTextField name, result; JLabel nameLabel, resultLabel; JButton search; JPanel panel; public NameLocator() { super("Search"); setSize(150, 160); name = new JTextField(10); result = new JTextField(10); nameLabel = new JLabel("Name to Find"); resultLabel = new JLabel("Result"); search = new JButton("Search for Name"); panel = new JPanel(); panel.add(name); panel.add(nameLabel); panel.add(result); panel.add(resultLabel); panel.add(search); setContentPane(panel); show(); MyListener listener = new MyListener(); search.addActionListener(listener); name.addActionListener(listener); } private class MyListener implements ActionListener { public void actionPerformed(ActionEvent e) { String line, filename = "c:\\names.txt"; try { FileReader fr = new FileReader(filename); BufferedReader in = new BufferedReader(fr); while ((line = in.readLine()) != null) { if (line.equals(name.getText())) { result.setText("Name found"); return; } } result.setText("Name not found."); } catch(FileNotFoundException exception) { System.out.println("File " + filename + " not found."); } catch(IOException exception) { System.out.println(exception); } } } } ******************* // Project ShortCircuit // Class Main public class Main { public static void main(String[] args) { int x, y; boolean f; x = 7; y = 20; // && uses short circuit evaluation. // If first term is false, don't evaluate // the second term. f = (x *= 2) > 15 && y-- == 20; System.out.println(x + " " + y + " " + f); x = 7; y = 20; // & uses complete evaluation. // Evaluate both terms. f = (x *= 2) > 15 & y-- == 20; System.out.println(x + " " + y + " " + f); // || uses short circuit evaluation. // If first term is true, don't evaluate // the second term. // | uses complete evaluation. // Evaluate both terms. } } ******************* // Project Tuple // Class Main // Test the equals method in the Tuple class. public class Main { public static void main(String[] args) { int i; Tuple v[] = new Tuple[5]; v[0] = new Tuple(4, 2); v[1] = new Tuple(4, 2, 8); v[2] = new Tuple(6, 9, 4, 6); v[3] = new Tuple(4, 2); v[4] = new Tuple(3, 0, 1); for(i = 0; i <= 4; i++) System.out.print(v[i] + " "); System.out.println(); System.out.print(v[2].equals(v[2]) + " "); System.out.print(v[0].equals(null) + " "); System.out.print(v[0].equals(v[3]) + " "); System.out.println(v[3].equals(v[1])); } } ******************* // Project Tuple // Class Tuple public class Tuple { private int[] array; // Constructor for tuple of size 1. public Tuple(int a) { array = new int[1]; array[0] = a; } // Constructor for tuple of size 2. public Tuple(int a, int b) { array = new int[2]; array[0] = a; array[1] = b; } // Constructor for tuple of size 3. public Tuple(int a, int b, int c) { array = new int[3]; array[0] = a; array[1] = b; array[2] = c; } // Constructor for tuple of size 4. public Tuple(int a, int b, int c, int d) { array = new int[4]; array[0] = a; array[1] = b; array[2] = c; array[3] = d; } public String toString() { String returnValue = "("; int i; for(i = 0; i <= array.length - 2; i++) returnValue += (array[i] + ","); returnValue += array[array.length - 1] + ")"; return returnValue; } public boolean equals(Tuple otherTuple) { int i; // This check insures v.equals(v) // is always true if v is an object. if (this == otherTuple) return true; // A nonnull object cannot be equal // to a null object. else if(otherTuple == null) return false; // Next check is to make sure that // v.equals(w) always equals w.equals(v) else if(getClass() != otherTuple.getClass()) return false; // Tuples cannot be equal if their // sizes are different. else if (array.length != otherTuple.array.length) return false; // Tuples of equal array sizes must match // in every component to be considered // equal. else { for(i = 0; i < array.length; i++) { if (array[i] != otherTuple.array[i]) return false; } return true; } } } ******************* // Project Tuple // Class Tuple public class Tuple { private int[] array; // Constructor for tuple of size 1. public Tuple(int a) { array = new int[1]; array[0] = a; } // Constructor for tuple of size 2. public Tuple(int a, int b) { array = new int[2]; array[0] = a; array[1] = b; } // Constructor for tuple of size 3. public Tuple(int a, int b, int c) { array = new int[3]; array[0] = a; array[1] = b; array[2] = c; } // Constructor for tuple of size 4. public Tuple(int a, int b, int c, int d) { array = new int[4]; array[0] = a; array[1] = b; array[2] = c; array[3] = d; } public String toString() { String returnValue = "("; int i; for(i = 0; i <= array.length - 2; i++) returnValue += (array[i] + ","); returnValue += array[array.length - 1] + ")"; return returnValue; } public boolean equals(Tuple otherTuple) { int i; // This check insures v.equals(v) // is always true if v is an object. if (this == otherTuple) return true; // A nonnull object cannot be equal // to a null object. else if(otherTuple == null) return false; // Next check is to make sure that // v.equals(w) always equals w.equals(v) else if(getClass() != otherTuple.getClass()) return false; // Tuples cannot be equal if their // sizes are different. else if (array.length != otherTuple.array.length) return false; // Tuples of equal array sizes must match // in every component to be considered // equal. else { for(i = 0; i < array.length; i++) { if (array[i] != otherTuple.array[i]) return false; } return true; } } } ******************* // Project Dialogs // Class Main public class Main { public static void main(String[] args) { // If you don't call getSize and show here, // be sure to call them in the MyFrame object. MyFrame x = new MyFrame(); } } ******************* // Project Dialogs // Class MyFrame import javax.swing.*; import java.awt.*; import java.awt.event.*; import javax.swing.JOptionPane; public class MyFrame extends JFrame { JButton a, b; JPanel p; // Save address of current window to pass to // JOptionPane.showMessageDialog method. MyFrame parentFrame = this; public MyFrame() { super("Dialogs"); a = new JButton("Dialog without parent."); b = new JButton("Dialog with parent"); p = new JPanel(); p.add(a); p.add(b); setContentPane(p); MyListener listener = new MyListener(); // Note: two controls add the same listener. // Use ActionListener.getSource to determine // in which control the click occurred. a.addActionListener(listener); b.addActionListener(listener); setSize(200, 150); show(); } private class MyListener implements ActionListener { public void actionPerformed(ActionEvent e) { // Show Message Dialog with no parent. if (e.getSource() == a) JOptionPane.showMessageDialog( null, "Dialog without parent."); // Show Message Dialog with MyFrame // window as parent. else if (e.getSource() == b) JOptionPane.showMessageDialog( parentFrame, "Dialog with parent."); } } } ******************* // Project DivideByZero // Class Main public class Main { public static void main(String[] str) { Divider x = new Divider(); } } ******************* // Project DivideByZero // Class Divider import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Divider extends JFrame { JLabel label1, label2, label3; JTextField dividend, divisor, quotient; JPanel panel; ReturnListener listener; public Divider() { super("Divider"); setSize(180, 120); label1 = new JLabel("Dividend"); label2 = new JLabel("Divisor "); label3 = new JLabel("Quotient"); dividend = new JTextField(8); divisor = new JTextField(8); quotient = new JTextField(8); panel = new JPanel(); listener = new ReturnListener(); panel.add(label1); panel.add(dividend); panel.add(label2); panel.add(divisor); panel.add(label3); panel.add(quotient); setContentPane(panel); dividend.addActionListener(listener); divisor.addActionListener(listener); quotient.addActionListener(listener); show(); } private class ReturnListener implements ActionListener { public void actionPerformed(ActionEvent e) { int x, y, z; try { x = Integer.parseInt(dividend.getText()); y = Integer.parseInt(divisor.getText()); z = x / y; quotient.setText(String.valueOf(z)); } catch(ArithmeticException exception) { quotient.setText("Zero Divisor"); System.out.println(exception); } catch(NumberFormatException exception) { quotient.setText("Bad Input"); System.out.println(exception); } } } } ******************* // Project StringTokenizer // Class Main // Read lines from a text file, using StringTokenizer // to find the fields in each line. // Avoid catch and try by declaring main as // throws IOException. import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { // Make sure that the input file is // moved to the correct drive and folder. FileReader fr = new FileReader("c:\\kids.txt"); // A BufferedReader reads one line at // at a time. BufferedReader br = new BufferedReader(fr); // line holds the line of text that the // BufferedReader extracts from the input. // If a line cannot be read, a null string // is returned. String line; // Variables to hold fields of input file. String name; int id; char gender; int age; int boyCount = 0, girlCount = 0; while ( (line = br.readLine()) != null) { // Set up StringTokenizer object for comma // delimited file. StringTokenizer st = new StringTokenizer(line, " ,\n"); name = st.nextToken(); id = Integer.parseInt(st.nextToken()); gender = (st.nextToken()).charAt(0); age = Integer.parseInt(st.nextToken()); if (st.hasMoreTokens()) System.out.println( "Extra characters " + "at end of line."); System.out.println( name + " " + id + " " + gender + " " + age); if (gender == 'F') girlCount++; else boyCount++; } System.out.println(); String message = "There are " + girlCount + " girls and " + boyCount + " boys."; System.out.println(message); // Write previous message to output file. // Change the file name to correct drive. FileWriter fw = new FileWriter("d:\\out.txt"); BufferedWriter bw = new BufferedWriter(fw); PrintWriter pw = new PrintWriter(bw); pw.println(message); // Output file must be closed to flush buffer. pw.close(); } } ******************* // Project TryCatch // Class Main // Process file one line at a time using // StringTokenizer to parse the fields in // each line. Use try and catch to handle // exceptions. import java.io.*; import java.util.*; public class Main { private static String fileName = "c:\\kids.txt"; public static void main(String[] args) { try { // Make sure that the input file is // moved to the correct drive and folder. FileReader fr = new FileReader(fileName); // A BufferedReader reads one line at // at a time. BufferedReader br = new BufferedReader(fr); // line holds the line of text that the // BufferedReader extracts from the input. // If a line cannot be read, a null string // is returned. String line; // Variables to hold fields of input file. String name; int id; char gender; int age; while ( (line = br.readLine()) != null) { // Set up StringTokenizer object for // comma delimited file. StringTokenizer st = new StringTokenizer(line, " ,\n"); name = st.nextToken(); try { id = Integer.parseInt( st.nextToken()); } catch(NumberFormatException e) { System.out.println(e); id = 99999; } gender = (st.nextToken()).charAt(0); try { age = Integer.parseInt( st.nextToken()); } catch(NumberFormatException e) { System.out.println(e); age = -1; } if (st.hasMoreTokens()) System.out.println( "Extra characters " + "at end of line."); System.out.println( name + " " + id + " " + gender + " " + age); } } catch(FileNotFoundException exception) { System.out.println( "File " + fileName + " not found."); } catch(IOException exception) { System.out.println(exception); } } } ******************* // Project ClickCounter // Class Main public class Main { public static void main(String[] args) { // Pass in size and caption to constructor. ClickCounter clickcounter = new ClickCounter(180, 120, "ClickCounter"); } } ******************* // Project ClickCounter // Class ClickCounter import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ClickCounter extends JFrame { // Reference instance variables for controls. JTextField numbClicks; JButton increment; JButton reset; JPanel panel; ClickListener clickListener; // Size and caption are set in main program. // They are passed in to constructor. public ClickCounter(int xSize, int ySize, String caption) { super(caption); setSize(xSize, ySize); numbClicks = new JTextField("0", 8); increment = new JButton("Click Me"); reset = new JButton("Reset"); panel = new JPanel(); clickListener = new ClickListener(); panel.add(numbClicks); panel.add(increment); panel.add(reset); // Create GridLayout with 3 rows, 1 column, // 5 pixels between rows, 5 pixels between // columns. panel.setLayout(new GridLayout(3, 1, 5, 5)); setContentPane(panel); show(); // Both buttons and the text box are connected // to the action listener object. The action // event occurs when a button is clicked or when // enter is pressed when the focus is in the // textbox. numbClicks.addActionListener(clickListener); increment.addActionListener(clickListener); reset.addActionListener(clickListener); } private class ClickListener implements ActionListener { // The virtual machine passes back the ActionEvent // object when the action event (click) occurs. public void actionPerformed(ActionEvent e) { int n; if (e.getSource() == increment || e.getSource() == numbClicks) { n = Integer.parseInt(numbClicks.getText()) + 1; numbClicks.setText(String.valueOf(n)); } else numbClicks.setText("0"); } } } ******************* // Project ShowWords // Class Main public class Main { public static void main(String[] args) { WordDisplayer wd = new WordDisplayer(); } } ******************* // Project ShowWords // Class WordDisplayer import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; public class WordDisplayer extends JFrame { // Instance variables. JTextField word; JButton next, first, choose; JPanel panel; String fileName; FileReader fr; BufferedReader inFile; JFileChooser chooser; ClickListener listener; boolean atEOF; WordDisplayer wdRef; public WordDisplayer() { // Set caption and size. super("Show Words"); setSize(180, 200); // Allocate space for controls and // listener. word = new JTextField(9); first = new JButton("First Word"); next = new JButton("Next Word"); choose = new JButton("Choose File"); panel = new JPanel(); chooser = new JFileChooser(); listener = new ClickListener(); wdRef = this; // Add controls for user interface. panel.add(word); panel.add(first); panel.add(next); panel.add(choose); setContentPane(panel); // Add listeners. first.addActionListener(listener); next.addActionListener(listener); choose.addActionListener(listener); // Show user interface. Note that user // interface is shown before the file // chooser is. show(); } public class ClickListener implements ActionListener { String line; public void actionPerformed(ActionEvent e) { try { // If "Get First" button is clicked // open input file, or reopen it if it // is open already. Then read the first // line in the file and display it. if(e.getSource() == first) { atEOF = false; fr = new FileReader(fileName); inFile = new BufferedReader(fr); line = inFile.readLine(); if (line == null) atEOF = true; else word.setText(line); } else if(e.getSource() == next) { // If at end of file, don't try to // read another line from file. if (!atEOF) { line = inFile.readLine(); if (line == null) atEOF = true; } // If at end of file, don't try to // copy word to textbox. if (!atEOF) word.setText(line); } else if (e.getSource() == choose) { // Set the starting directory for the // FileChooser, show the open dialog and // get the path for the file. chooser.setCurrentDirectory( new File("d:\\")); chooser.showOpenDialog(wdRef); fileName = chooser.getSelectedFile() .getPath(); word.setText(""); } } catch(IOException exception) { System.out.println(exception); } } } } ******************* // Project Interface // Class Test // Test the Philosopher and Dog classes which // each implement the Speaker interface. public class Test { public static void main(String[] args) { Philosopher x = new Philosopher("I think, therefore I am."); Dog y = new Dog(); x.speak(); y.speak(); x.announce("To be, or not to be, that is " + "the question."); y.announce("Its a dog's life."); x.pontificate(); System.out.println(); Speaker u, v; u = x; v = y; u.speak(); v.speak(); ((Philosopher) u).pontificate(); } } ******************* // Project Interface // Class Philospher public class Philosopher implements Speaker { private String philosophy; public Philosopher(String aPhilosophy) { philosophy = aPhilosophy; } public void speak() { System.out.println(philosophy); } public void announce(String announcement) { System.out.println(announcement); } public void pontificate() { int i; for(i = 1; i <=5; i++) System.out.println(philosophy); } } ******************* // Project Interface // Class Dog public class Dog implements Speaker { public void speak() { System.out.println("woof"); } public void announce(String announcement) { System.out.println("woof: " + announcement); } } ******************* // Project Interface // Interface Speaker // Any class that implements this interface // must provide implementations for the // speak and announce methods. public interface Speaker { public void speak(); public void announce(String str); } ******************* // Project Sorter // Class Main public class Main { public static void main(String[] args) { // Determine maximum size of sorter. Sorter s = new Sorter(20); // Add kid objects to sorter. s.add(new Kid("Jane", 4565, 'F', 9)); s.add(new Kid("Bill", 2837, 'M', 10)); s.add(new Kid("Susan", 9837, 'F', 8)); s.add(new Kid("Ken", 5384, 'M', 11)); s.add(new Kid("Barb", 3723, 'F', 10)); s.add(new Kid("Sam", 5384, 'M', 8)); // Print unsorted list. System.out.println(s); // Sort list. s.sort(); // Print sorted list. System.out.println(s); } } ******************* // Project Sorter // Class Sorter // An object of the Sorter class sorts // Comparable objects, i.e., objects that // implement the Comparable interface. // The Sorter is like a Stack with the // extra methods sort and toString. // The add method is really the Stack // pop method. public class Sorter { private int size; private Comparable[] array; public Sorter(int aSize) { array = new Comparable[aSize]; size = 0; } public void add(Comparable x) { array[size++] = x; } public String toString() { String retVal = "{"; int i; for(i = 0; i <= size - 2; i++) retVal += array[i] + ","; retVal += array[size - 1] + "}"; return retVal; } // The implementation of this sort method // is BubbleSort. Substitute a more efficient // sorting algorithm if you wish. public void sort() { int i, j; Comparable temp; for(i = 0; i <= size - 2; i++) for(j = i + 1; j <= size - 1; j++) { // Swap a pair of array elements // if they are out of order. if (array[i].compareTo(array[j]) > 0) { temp = array[i]; array[i] = array[j]; array[j] = temp; } } } } ******************* // Project Sorter // Interface Comparable public interface Comparable { // For the Sorter object to be able to // sort objects such as Kid objects, // the Kid class must implement a compareTo // method. public int compareTo(Object c); } ******************* // Project Sorter // Interface Comparable public interface Comparable { // For the Sorter object to be able to // sort objects such as Kid objects, // the Kid class must implement a compareTo // method. public int compareTo(Object c); } ******************* // Project Sorter // Class Kid // The Kid class implements the Comparable interface // so that Kid objects can be sorted by a // Sorter object. public class Kid implements Comparable { // Private instance variables. protected String name; private int id; private char gender; private short age; // Default constructor. public Kid() { // Initialize to default values. name = "Unknown"; id = 99999; gender = 'U'; age = -1; } // Parameterized constructor. public Kid(String aName, int anId, char aGender, int anAge) { // name is not the null string. if (aName.equals("")) name = "Unknown"; else name = aName; // id is between 0 and 99999. if (anId < 0 || anId > 99998) id = 99999; else id = anId; // Gender is 'F', 'M', or 'U'. if (aGender != 'F' && aGender != 'M') gender = 'U'; else gender = aGender; // Age is nonnegative. if (anAge < 0) age = (short) -1; age = (short) anAge; } // Accessor method for name. public String getName() { return name; } // Accessor method for id. public int getId() { return id; } // Accessor method for gender. public char getGender() { return gender; } // Accessor method for age. public short getAge() { return (short) age; } // Mutator method for age. public void hasBirthday() { age++; } // Print method. public String toString() { return "[" + name + ";" + id + ";" + gender + ";" + age + "]"; } public int compareTo(Object other) { // Return a positive integer if // this "is less than" other. // Return a negative integer if // this "is greater than" other. // Return zero if this "equals" other. // The String compareTo follows this // convention. return name.compareTo(((Kid) other).name); } } *******************