************************** // Project Convert // Class Convert // Illustrate how to convert to and from a string. public class Convert { public static void main(String[] args) { int x = 354; double y = 8.3278; String a, b; // Convert x and y to the String // objects a and b. a = String.valueOf(x); b = String.valueOf(y); System.out.println(a + " " + b); // Convert a and b back to int and double. // In C++ these are the atoi and atof // functions. x = 0; y = 0; x = Integer.parseInt(a); y = Double.parseDouble(b); System.out.println(a + " " + b); } } // Output: true true true true true true S true true true true 354 8.3278 354 8.3278 ************************** // Project TestKid // Class TestKid // Text the Kid class in the main method. public class TestKid { public static void main(String[] args) { // Declare 2 reference variables for Kid class. Kid kid1, kid2; // Create 2 Kid objects. kid1 = new Kid(); kid2 = new Kid("Brittany", 36594, 'F', 9); // Test accessor methods. System.out.print(kid2.getName() + " " ); System.out.print(kid2.getId() + " " ); System.out.print(kid2.getGender() + " " ); System.out.println(kid2.getAge()); // Test print method. System.out.println(); kid1.print(); kid2.print(); // Test hasBirthday method. kid2.hasBirthday(); kid2.print(); // Change reference of kid2 to kid1. kid1 = kid2; kid1.print(); kid2.print(); } } // Output: Brittany 36594 F 9 name=Unknown id=99999 gender=U age=-1 name=Brittany id=36594 gender=F age=9 name=Brittany id=36594 gender=F age=10 name=Brittany id=36594 gender=F age=10 name=Brittany id=36594 gender=F age=10 ************************** // Kid1 Project // Kid Example public class Kid { // Private instance variables. private 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 void print() { System.out.print("name=" + name + " " ); System.out.print("id=" + id + " " ); System.out.print("gender=" + gender + " "); System.out.println("age=" + age + '\n'); } } ************************** // Project TestClock // Class TestClock public class TestClock { public static void main(String args[]) { int i; Clock clock = new Clock(13, 43, 21); // Test display and tick methods. clock.display(); clock.tick(); clock.display(); clock.tick(); for(i = 1; i <= 50000; i++) clock.tick(); clock.display(); } } // Output: 13:43:21 13:43:22 03:36:43 ************************** // Project Clock // Class Clock import java.text.DecimalFormat; public class Clock { private int hours; private int minutes; private int seconds; // Default constructor. public Clock() { hours = 0; minutes = 0; seconds = 0; } // Parameterized constructor. public Clock(int h, int m, int s) { // Set time according to parameters. hours = h % 24; minutes = m % 60; seconds = s % 60; } // Add one to seconds. public void tick() { seconds++; // If seconds == 60, increment minutes. if (seconds >= 60) { seconds = 0; minutes++; } // If minutes == 60, increment hours. if (minutes >= 60) { minutes = 0; hours++; } // If hours == 24, go back to 0. if (hours == 24) { hours = 0; } } public void display() { DecimalFormat fmt = new DecimalFormat("00"); System.out.println(fmt.format(hours) + ":" + fmt.format(minutes) + ":" + fmt.format(seconds)); } } ********************* // Project Finalize // Class Main public class Main { public static void main(String[] args) { Test a = new Test(7, 'R'); a.print(); a = null; System.gc(); } } Output:// In constructor 7 R In finalize ********************* // Project Finalize // Class Test public class Test { public int x; public char y; public Test(int anX, char aY) { System.out.println("In constructor"); x = anX; y = aY; } public void print() { System.out.println(x + " " + y); } public void finalize() { System.out.print("In finalize "); print(); } } ********************* // Project PigLatin // Project PigLatinTest // Translate English into Pig Latin // Based on Lewis and Loftus example on Page 207. import cs1.Keyboard; public class PigLatinTest { public static void main() { String englishSentence, pigLatinSentence; PigLatinTranslator translator = new PigLatinTranslator(); englishSentence = Keyboard.readString(); pigLatinSentence = translator.translatePhrase(englishSentence); System.out.println(pigLatinSentence); } } // Output: This is a test isthay isyay ayay esttay ********************* // Project PigLatin // Class PigLatinTranslator // Translate English into Pig Latin. // Based on Lewis and Loftus example on Page 207. import java.util.StringTokenizer; public class PigLatinTranslator { public String translatePhrase(String phrase) { String result = ""; phrase = phrase.toLowerCase(); StringTokenizer tokenizer = new StringTokenizer(phrase); while(tokenizer.hasMoreTokens()) { result += translateWord( tokenizer.nextToken()); result += " "; } return result; } public String translateWord(String word) { String result = ""; if (beginsWithVowel(word)) result = word + "yay"; else if(beginsWithPrefix(word)) result = word.substring(2) + word.substring(0,2) + "ay"; else result = word.substring(1) + word.charAt(0) + "ay"; return result; } // Return true if word begins with vowel. private boolean beginsWithVowel(String word) { String vowels = "aeiouAEIOU"; char letter = word.charAt(0); return vowels.indexOf(letter) != -1; } // Return true if word begins with one of // following prefixes. private boolean beginsWithPrefix(String w) { return w.startsWith("bl") || w.startsWith("pl") || w.startsWith("br") || w.startsWith("pr") || w.startsWith("ch") || w.startsWith("sh") || w.startsWith("cl") || w.startsWith("sl") || w.startsWith("cr") || w.startsWith("sp") || w.startsWith("dr") || w.startsWith("sr") || w.startsWith("fl") || w.startsWith("st") || w.startsWith("fr") || w.startsWith("th") || w.startsWith("gl") || w.startsWith("tr") || w.startsWith("gr") || w.startsWith("wh") || w.startsWith("kl") || w.startsWith("wr") || w.startsWith("ph"); } } ********************* // Project IntArray // Class IntArray public class IntArray { public static void main(String[] args) { int i, sum; // Declare reference variable for array. int[] a; // Allocate space for array. a = new int[5]; // Set values of the array. a[0] = 34; a[1] = 75; a[2] = 91; a[3] = 11; a[4] = 50; // Print the array. for(i = 0; i < 5; i++) System.out.print(a[i] + " "); System.out.println(); // Print sum of array elements. sum = 0; for(i = 0; i < 5; i++) sum += a[i]; System.out.println("The sum is " + sum + "."); } } // Output: 34 75 91 11 50 The sum is 261. **************************** // Project KidArray // Class KidArrayTest // Create an array of Kid objects. public class KidArrayTest { public static void main(String[] args) { int i; // Declare Kid array. Kid[] kid; // Allocate space for Kid array. // After this, we still must put the Kid // objects into the array. kid = new Kid[4]; // Create Kid objects in array. kid[0] = new Kid("Jessica", 37463, 'F', 9); kid[1] = new Kid("Kevin", 55986, 'M', 10); kid[2] = new Kid("Katie", 86372, 'F', 11); kid[3] = new Kid(); // Print all the kids in the array. for(i = 0; i < 4; i++) kid[i].print(); // Get the name of the 2nd kid in the array. System.out.println(kid[2].getName()); } } // Output: name=Jessica id=37463 gender=F age=9 name=Kevin id=55986 gender=M age=10 name=Katie id=86372 gender=F age=11 name=Unknown id=99999 gender=U age=-1 Katie ********************** // Project KidArray // Class Kid The source code for this class is the same as it is in the Kid1 project above. ********************** // Project TestStack // Class TestStack // Create and test Stack of char. public class TestStack { public static void main() { boolean r; Stack x = new Stack(5); r = x.push('M'); System.out.print(r + " "); r = x.push('Y'); System.out.print(r + " "); r = x.push('S'); System.out.print(r + " "); r = x.push('B'); System.out.print(r + " "); r = x.push('P'); System.out.println(r); System.out.println(x.isFull()); x.pop(); x.pop(); System.out.print(x.top() + " "); System.out.print(x.pop() + " "); System.out.print(x.pop() + " "); System.out.println(x.pop()); System.out.println(x.isEmpty()); } } // Output: true true true true true true S true true true true ********************** // Project CharStack // Class Stack // Implementation of a stack of char. public class Stack { private char[] array; private int top; private int size; public Stack(int n) { size = n; array = new char[size]; top = -1; } public boolean push(char letter) { if (top < size - 1) { array[++top] = letter; return true; } else return false; } public boolean pop() { if (top >= 0) { top--; return true; } else return false; } public char top() { return array[top]; } public boolean isEmpty() { return top == -1; } public boolean isFull() { return top == size - 1; } } ********************** // Project Derived // Class Test public class Test { public static void main() { Derived x = new Derived(); Derived y = new Derived("premier", "deuxieme"); // The toString method of the Object class // is invoked to print. This method can be // overridden. System.out.println(x.a + " " + x.b); System.out.println(y.a + " " + y.b); } } // Output: Default Base Constructor, value of a = first Derived constructor, value of b = second Parameterized Base Constructor, value of a = premier Derived constructor, value of b = deuxieme first second premier deuxieme ********************** // Project Derived // Class Base public class Base { // Default constructor will assign the instance // variable a the string "first". // Parameterized constructor will will assign // b a string to be passed in. public String a; // Default constructor using English. public Base() { a = "first"; System.out.println("Default Base " + "Constructor, value of a = " + a); } // Parameterized constructor. public Base(String str) { a = str; System.out.println("Parameterized Base " + "Constructor, value of a = " + a); } } ********************** public class Derived extends Base { // Default constructor will assign the instance // variable b the string "second". // Parameterized constructor will will assign // b a string to be passed in. public String b; // Default constructor, uses English. public Derived() { // The default constructor of the base // class is invoked first, unless there is // an invocation of a different constructor // using super. b = "second"; System.out.println("Derived constructor," + " value of b = " + b); } // Parameterized constructor. It calls the // parameterized constructor in the Base class. public Derived(String str1, String str2) { // Invoke parameterized constructor from // the base class. super(str1); b = str2; System.out.println("Derived constructor," + " value of b = " + b); } } ********************** // Project Messages // Class Messages // Note: Advice starts as a thought, but not // all thoughts qualify as advice. Therefore // the class Advice inherits the class Thought. // In Java, all methods act as virtual methods. // Their action depends on the type of object from // which are invoked, as specified in the new statement, // not the type of the reference variable containing // the address of the object. public class Messages { public static void main(String[] args) { Thought a = new Thought(); Advice b = new Advice(); Thought c = new Advice(); Object d = new Thought(); Object e = new Advice(); // Invoke message method of a. a.message(); // Invoke overridden message method of b. b.message(); // c can refer to Advice object, even though // it is declared as c.message(); // Invokes the toString methods for d and e. System.out.println(d); System.out.println(e); } } ********************** // Project Message // Class Thought // A stray thought that may or may not qualify // as advice. public class Thought { public void message() { System.out.println("I feel like I am " + "diagonally parked in a parallel universe.\n"); } } // Output: I feel like I am diagonally parked in a parallel universe. Dates in calendar are closer than they appear. I feel like I am diagonally parked in a parallel universe. Dates in calendar are closer than they appear. I feel like I am diagonally parked in a parallel universe. Thought@ff5b702b Advice@ff5b7012 ********************** // Project Message // Class Advice public class Advice extends Thought { public void message() { System.out.println("Dates in calendar are " + "closer than they appear."); super.message(); } } ********************** // Project Temperture1 // Class TempConverter // Convert a Fahrenheit temperature to Celsius // Adapted from Lewis and Loftus, Page 363. // import applet and event model definitions. import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class TempConverter extends Applet implements ActionListener { // Set dimensions of applet. private final int APPLET_WIDTH = 200; private final int APPLET_HEIGHT = 100; // Declare instance variables for controls. private Label inputLabel, outputLabel, resultLabel; private TextField fahrenheit; // Set up controls on applet when applet // is initialized. public void init() { // Create labels. inputLabel = new Label("Enter Fahrenheit"); outputLabel = new Label("Temperature in Celsius"); resultLabel = new Label("N/A"); // Create textfield and add action listener. fahrenheit = new TextField(5); fahrenheit.addActionListener(this); // Add controls to applet. add(inputLabel); add(fahrenheit); add(outputLabel); add(resultLabel); // Set background color and size of applet. setBackground(Color.white); setSize(APPLET_WIDTH, APPLET_HEIGHT); } // This method must be implemented for the // ActionListener class. public void actionPerformed(ActionEvent e) { int f, c; // Get fahrenheit temperature from textfield, // convert to temperature, and put in // resultLabel. String fstring = fahrenheit.getText(); f = Integer.parseInt(fstring); c = (f - 32) * 5 / 9; resultLabel.setText(Integer.toString(c)); } } ********************** // Project Temperature2 // Class Test public class Test { public static void main(String[] args) { TempConverter frame = new TempConverter(); frame.show(); } } ********************** // Project Temperature2 // Class TempConverter // A user interface that converts from Fahrenheit // to Celsius. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class TempConverter extends JFrame { // Declare controls for frame. JLabel fLabel, cLabel; JTextField fText, cText; JButton convertButton; JPanel panel; public TempConverter() { // Set properties of frame super("C to F Conv"); setSize(170, 150); // Allocate space for controls. fLabel = new JLabel("Fahrenheit"); cLabel = new JLabel("Celsius"); fText = new JTextField(5); cText = new JTextField(5); convertButton = new JButton("Convert"); // Allocate space for panel. panel = new JPanel(); // Add controls to panel. panel.add(fLabel); panel.add(fText); panel.add(cLabel); panel.add(cText); panel.add(convertButton); // Set panel as the content pane of // the frame. setContentPane(panel); SubmitActionListener actionListener = new SubmitActionListener(); convertButton.addActionListener(actionListener); } // Inner class SubmitActionListener // to handle click events for submit button. // The inner class has access to the private // instance variables of the containing class // TempConverter. public class SubmitActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { int c, f; f = Integer.parseInt(fText.getText()); c = 5 * f / 9; cText.setText(Integer.toString(c)); } } }