Skip to main content

Course Package 1

Hello.java

 /* File: Hello.java
 
    This is a simple sample standalone text-based Java application.
    Output is generated to StdOut (Standard Out), which in this case is the user's console.
 
    In a Java application, execution begins with the main() method (defined below).
 
    If you're working from the command line (such as on mislab)
    compile and execute this program with the commands:
 
      javac Hello.java                   (creates Hello.class)
      java  Hello                        (runs the JVM to execute byte code)
 
    (Note: The file names in these commands are case-sensitive.)
 
    javac.exe is the Java compiler. javac translates source code (stored in
    a .java file) into platform-independent byte code (stored in a .class
    file). Byte code is interpreted and executed by a JVM (Java Virtual Machine).
 
    java.exe is a JVM. Some consumer electronics are hardware JVM's (their electronics can
    actually interpret and execute Java byte code). A JVM is platform-dependent.
    That is, you must have a JVM that runs in your environment.
 
    The main method must be defined as it is in the example below. The only
    thing that you can change is the name of the parameter (args).
 
    The main method receives an Array of String objects.
 
     Some elements of programming style which are demonstrated here:
    1. the class name begins with an upper-case letter
    2. corresponding curly braces are aligned
    3. statements within a body of code are indented
    4. blank lines are used to enhance readability
    5. comments are used to enhance readability and understandability
 
 */
 




 public class Hello                              // Hello class header
 {                                               // the body of the class is enclosed in curly braces,
                                                 // which are aligned to enhance readability
 
   public static void main(String[] args)        // main() method header; execution begins here
   {                                             // the body of the method is enclosed in curly braces
 
     System.out.println("Hello world");          // call the println method to generate output
                                                 // to StdOut
   }
 
 }
 // You should type this program, compile it, and execute it to test your Java environment.

DOS1a.java

// You should type this program, compile it, and execute it to test your Java environment.
 /* File: DOS1a.java
 
    DOS1a uses a "for loop" to calculate the sum of the integers between
    two hard-coded values.
 
    This program uses three primitive int scalar variables. There are eight types of
    primitives in Java: boolean, char, byte, short, int, long, float, double.
    Everything else is object-oriented!
 
 */
 
 public class DOS1a                                      // DOS1a class header
 {
   public static void main(String[] args)                // main() method header
   {
     int start,stop,sum;                                 // define (declare) 3 primitive int variables
                                                         // this defines name, data type, and size
                                                         // these variables have "block scope"; they are
                                                         // visible until the } at the end of this block
                                                         // of code (this method)
 
     start=11;                                           // initialize the variables (give each a value)
     stop=20;
     sum=0;
 
     for(int i=start;i<=stop;i++)                        // for loop; "i" has block scope; its life is
                                                         // the block of this for loop
     {
       System.out.println(i);                            // print value of "i" to StdOut, followed by LF
       sum=sum+i;                                        // accumulate running total
     }
                                                         // i is no longer available
     System.out.println("\n"+sum);                       // print blank line, then value of "sum"
   }
 }

DOS1b.java

/* File: DOS1b.java
 
    DOS1b uses a hard-coded, comma-delimited string of Fahrenheit temperatures as its input.
    It uses the String class's split method to split that string apart into its separate values,
    then converts those values to Centigrade.
 
    This program uses the "split" method from the String class. The documentation of the String
    class describes the "interface" of the method: what you pass to the method, and what
    the method returns to you. The following comes from the documentation of the method:
    (textbook: page 431)
    
    public String[] split(String s)
    
    This tells you that:
 split is an instance method (the method header does not include the word "static");
       because it's an instance method, it "operates on" a String object; in calling this method,
       use a String object to the left of the dot
 the method accepts a String object as its sole parameter
 the method returns an array of String objects
 
    This program uses the length property of an Array object to know the number of
    elements in the array (inputs.length).
 
    This program uses the "parseDouble" method from the Double class. The documentation of the Double
    class describes the interface of the "parseDouble" method: what you pass to the method, and what
    the method returns to you. The following comes from the documentation of the method:
    (textbook: page 445)
 
    public static double parseDouble(String s)
 
    This tells you that:
 parseDouble is a class method (the method header includes the word "static"); in calling
       this method, use the name of its class to the left of the dot: Double.parseDouble()
 it accepts a String object as its sole parameter
 it returns a double primitive
 
 */
 
 public class DOS1b
 {
 
   public static void main(String[] args)
   {
 
     String string="0,32,100,212";
     String[] inputs=string.split(",");                  // define an array of String objects
                                                         // split the initial string to populate that array
     
     for(int i=0;i<inputs.length;i++)                    // step through the elements in the array
     {                                                   //  (use length property of the Array object)
       String s=inputs[i];                               // get next element
       double f=Double.parseDouble(s);                   // call parseDouble class method (of Double class)
       double c=(f-32)*5/9;                              // now calculate Celsius temp
 
       System.out.println(f+"F = "+c+"C");               // concatenated items for output
     }
 
   }
 }

DOS1c.java

 /* File: DOS1c.java
 
    This program accepts both integer and double input from the keyboard.
    It uses the Utility.readInt() method to read an int value, and the
    Utility.readDouble() method to read doubles. Both of these methods are
    user-defined methods, contained in the Utility class, which is stored
    in Utility.java.
 
    Utility.java is a user-defined class that is available on our course web site.
 
    Note that methods from the Utility class are not compiled INTO your byte
    code. A separate Utility.class is created by the compiler. You need
    Utility.class in the directory along with your program when you try to
    run your program.
 
    In this program, the user can enter a series of double values, which are
    stored in an array. The array is sorted, and the sorted list is displayed
    on the screen.
 
    The "sort" method from the Arrays class is used in this program (textbook: page 558).
    The Arrays class is stored in the java.util package. The import statement is used to make
    this class available to the compiler.
 
 */
 
 import java.util.*;                                     // make classes and interfaces from the
                                                         // java.util package available to the compiler
 
 public class DOS1c
 {
   public static void main(String[] args)
   {
     int     limit;                                      // define int scalar
     double[] doubleArray;                               //  and array of primitive doubles
 
                                                         // at this point, the value of doubleArray is: null
                                                         // if you try to refer to doubleArray's value,
                                                         //  you will get a nullPointerException
 
     System.out.println("How many values? ");            // display prompt for input
     limit=Utility.readInt();                            // use Utility.readInt() to accept input
 
     doubleArray=new double[limit];                      // allocate memory for array of "limit" double elements
                                                         // doubleArray is an Array object
                                                         // each element in the array will be a primitive double
 
     System.out.println();                               // print a blank line
     for(int i=0;i<limit;i++)                            // loop to get input values
     {                                                   //  ++ is the increment operator
       System.out.println("next value? ");
       doubleArray[i]=Utility.readDouble();              // read next double into array
     }
 
     Arrays.sort(doubleArray);                           // use Arrays.sort to sort our array
 
     System.out.println("\nYour output is:");
     for(int i=0;i<doubleArray.length;i++)               // step through array, generate output
     {
       System.out.println(doubleArray[i]);
     }
   }
 }

DOS2a.java

/* File: DOS2a.java
 
    This program instantiates a "Person" object (an instance of the "Person" class).
    It then uses some of the properties and methods of a Person object.
 
    The Person class is defined in Person.java (the next class in this course packet).
    This is a user-defined class; it is not part of the standard Java API.
 */
 
 public class DOS2a
 {
   public static void main(String[] args)
   {
     Person subject;                                             // define a Person reference variable;
                                                                 //  allocate memory for a reference variable
                                                                 //  that will contain the memory address
                                                                 //  of a Person object
 
     subject=new Person();                                       // instantiate a Person object by calling the
                                                                 //  Person class's zero-argument constructor
                                                                 // assign its memory address to the reference
                                                                 //  variable "subject"
 
     subject.lastName="Gilligan";                                // assign values to properties
     subject.firstName="Thom";
     subject.age=61;
     
     System.out.println("\nThe first Person is:");
     System.out.println(subject.toString()+"\n\n");
 
 
     subject=new Person("Buck","Logan",52);                      // instantiate another Person object
                                                                 //  by calling its constructor method
                                                                 //  that accepts String, String, int
 
     System.out.println("Last Name: "+subject.lastName);         // access the "lastName" property of the object
     System.out.println("    First: "+subject.firstName);
     System.out.println("      Age: "+subject.age+"\n");
 
     subject.age++;                                              // increment the value of the "age" property
 
     System.out.println("Last Name: "+subject.lastName);
     System.out.println("    First: "+subject.firstName);
     System.out.println("      Age: "+subject.age+"\n");
     System.out.println("   Packed: "+subject.toString());       // use the "toString()" method
 
   }
 }

Person.java

/* File: Person.java
 
    This file defines the Person class, which can be used to instantiate a
    Person object.
 
    In object-oriented analysis, design, and programming, you try to identify the
    objects that are the components of a system. Then you develop a class (a blueprint)
    for each of these types of objects.
 
    When you write a class to represent an object, such as a Person, ask yourself:
 What are the attributes of a Person object?
 What methods does the class need, to operate on a Person object?
 
   A "constructor method" is called to instantiate an instance of a class, such as:
     new Person();
     
   The name of a constructor must match the name of the class (in this case, Person).
   This is a unique characteristic of constructor methods, when compared to other methods:
   a constructor method's name begins with an upper-case letter, since it must match the
   name of the class (which, by convention, begins with an upper-case letter).
   
   A constructor method may NOT specify a return data type.
   
   public Person()         is a constructor method
   public void Person()    is not a constructor method
 
 */
 
 public class Person
 {
   public int    age;                                    // instance variable (property, attribute)
   public String lastName,firstName;                     // instance variables
 
   public Person()                                       // zero-argument constructor method
   {
     this.age=0;                                         // initialize properties with default values
     this.lastName="";
     this.firstName="";
   }                                                     // constructor may not have a return
                                                         //  and may not specify a return data type
 
   public Person(String s1,String s2,int i)              // constructor, accepts three parameters
                                                         //  String, String, int
   {
     this.firstName=s1;                                  // set the properties of this object
     this.lastName=s2;                                   //  based on received parameters
     this.age=i;
   }
 
   public String toString()                              // instance method (not static)
   {
     return this.firstName.trim()+" "+this.lastName.trim();  // build string, then return it
   }
 }

DOS2b.java

/* File: DOS2b.java
 
    This program uses the NewPerson class rather than the Person class.
 
    NewPerson demonstrates "data hiding" and better "encapsulation" by making its
    properties private, and providing accessor and mutator methods for those properties.
 
 */
 
 public class DOS2b
 {
   public static void main(String[] args)
   {
     NewPerson subject=new NewPerson();          // declare a NewPerson reference variable
                                                 //  and instantiate a NewPerson object
 
     subject.setFirstName("Buck");               // call mutator methods to change values
     subject.setLastName("Logan");
     subject.setAge(52);
 
     System.out.println("First Name: "+subject.getFirstName());
     System.out.println(" Last Name: "+subject.getLastName());
     System.out.println("       Age: "+subject.getAge());
     System.out.println();
 
     subject.setFirstName("Charles");
     subject.setLastName("");                    // can you set the last name to null?
     if(!subject.setAge(-1))                     // can you set the age to a negative value?
     {
       System.out.println("Error changing age.\n\n");
     }
 
     System.out.println("First Name: "+subject.getFirstName());
     System.out.println(" Last Name: "+subject.getLastName());
     System.out.println("       Age: "+subject.getAge());
     System.out.println();
   }
 }

NewPerson.java

/* File: NewPerson.java
 
    The NewPerson class modifies the Person class. In particular,
    the properties of this class are declared private so that outside
    classes can not directly manipulate the values of the properties.
    To retrieve or change the value of firstName, lastName, or age
    (the properties of a NewPerson object), you have to call the appropriate
    accessor (get...) or mutator (set...) method.
 
    Encapsulation is an important concept in object-oriented programming.
    When we define a class, we want to include all relevant properties and
    methods of the class in that class. We want to encapsulate the attributes
    and behaviors of instances of that class, minimizing interactions with
    the outside.
 
    By making properties private, we have control over the values assigned
    to those properties. Our mutator methods can do whatever error-checking
    is appropriate before modifying a property. Even in accessor methods,
    we can implement whatever controls are appropriate to access the value
    of a property.
 
    Although it adds more programming, adding accessor and mutator methods,
    and making properties private, is an important component of encapsulation.
 
    The name of an accessor method, by convention, begins with the word "get",
    followed by the name of the associated property (capitalizing the first
    letter of the property name). See examples in this class.
 
    The name of a mutator method, by convention, begins with the word "set",
    followed by the name of the associated property (capitalizing the first
    letter of the property name). See examples in this class.
 
 */
 
 public class NewPerson
 {
   private String firstName,lastName;            // private instance variables (properties)
   private int    age;
 
   public NewPerson()                            // zero-argument constructor method
   {
     this.firstName="";                          // default values for properties
     this.lastName="";
     this.age=0;
   }
 
   public String getFirstName()                  // accessor method to retrieve value of firstName
   {                                             // returns a String
     return this.firstName;
   }
 
   public boolean setFirstName(String s)         // method to change value of firstName
   {                                             //  returns a primitive boolean
     if(s.length()==0)                           // call length() method of String object
     {                                           // don't change firstName to null String
       return false;
     }
 
     this.firstName=s;                           // change firstName
 
     return true;                                // value was changed
   }
 
   public String getLastName()                   // accessor method to retrieve value of lastName
   {                                             // returns a String
     return this.lastName;
   }
 
   public boolean setLastName(String s)          // method to change value of lastName
   {
     if(s.length()==0)                           // call length() method of String object
     {                                           // don't change lastName to null String
       return false;
     }
 
     this.lastName=s;                            // change lastName
 
     return true;                                // value was changed
   }
 
   public int getAge()                           // accessor method to retrieve value of age
   {                                             // returns an int value
     return this.age;                            // return value of this.age
   }
 
   public boolean setAge(int i)                  // mutator method to change value of age
   {                                             // returns boolean indicating if value was changed
     if(i<0)                                     // don't change age to negative value
     {
       return false;                             // value was not changed
     }
     this.age=i;                                 // i >= 0, valid value
     return true;                                // value was changed
   }
 
 }

DOS2c.java

/* File: DOS2c.java
 
    This system uses three classes: DOS2c, NewerPerson, and Employee.
    The Employee class is a subclass of the NewerPerson class. This program
    instantiates an Employee object.
 
 */
 
 public class DOS2c
 {
   public static void main(String[] args)
   {
     Employee subject;
 
     subject=new Employee(101,"Barney","Fife",51,17.25);     // instantiate an Employee object
 
     System.out.println("   EmpNum: "+subject.getEmpNum());  // call several of the object's instance methods
     System.out.println("Last Name: "+subject.getLastName());
     System.out.println("    First: "+subject.getFirstName());
     System.out.println("      Age: "+subject.getAge());
     System.out.println("     Rate: "+subject.getPayRate());
     System.out.println("\n"+subject.toString()+"\n\n\n");
   }
 }

NewrPerson.java

/* File: NewerPerson.java
 
    The NewerPerson class modifies the NewPerson class.
 
    The NewPerson class used private instance variables (properties). But we now want to
    be able to subclass the NewPerson class to further define a specific type of NewPerson,
    an Employee. The problem is that private properties may not be accessed by other classes,
    even by a subclass. NewerPerson changes the access modifier on those properties to protected,
    rather than private.
 
 */
 
 public class NewerPerson
 {
   protected String firstName,lastName;          // protected instance variables
   protected int    age;
 
   public NewerPerson()                          // constructor method
   {
     this.firstName="";                          // default values for properties
     this.lastName="";
     this.age=0;
   }
 
   public NewerPerson(String f,String l,int i)   // overloaded constructor method
   {
     this.firstName=f;                           // set values for properties
     this.lastName=l;
     this.age=i;
   }
 
   public String getFirstName()                  // accessor method to retrieve value of firstName
   {                                             // returns a String
     return this.firstName;
   }
 
   public boolean setFirstName(String s)         // method to change value of firstName
   {
     if(s.length()==0)                           // call length() method of String object
     {                                           // don't change firstName to null String
       return false;
     }
 
     this.firstName=s;                           // change firstName
 
     return true;                                // value was changed
   }
 
   public String getLastName()                   // accessor method to retrieve value of lastName
   {                                             // returns a String
     return this.lastName;
   }
 
   public boolean setLastName(String s)          // method to change value of lastName
   {
     if(s.length()==0)                           // call length() method of String object
     {                                           // don't change lastName to null String
       return false;
     }
 
     this.lastName=s;                            // change lastName
 
     return true;                                // value was changed
   }
 
   public String getName()
   {
     return this.lastName.trim()+", "+this.firstName.trim();
   }
 
   public int getAge()                           // accessor method to retrieve value of age
   {                                             // returns an int value
     return this.age;                            // return value of this.age
   }
 
   public boolean setAge(int i)                  // mutator method to change value of age
   {                                             // returns boolean indicating if value was changed
     if(i<0)                                     // don't change age to negative value
     {
       return false;                             // value was not changed
     }
     this.age=i;                                 // i >= 0, valid value
     return true;                                // value was changed
   }
 
 }

Employee.java

/* File: Employee.java
 
    Object
      |
      +---NewerPerson
            |
            +---Employee
 
    The Employee class subclasses the NewerPerson class (which subclasses the Object class).
    Therefore, Employee inherits properties and methods of the superclass (NewerPerson).
    It may optionally over-ride any property or method that would otherwise be inherited
    (this is done with the toString() method, below).
 */
 
 public class Employee extends NewerPerson               // subclass the NewerPerson class
 {
   protected Integer empNum;                             // add specific properties of the subclass
   protected double payRate;
 
   public Employee()                                     // zero-argument constructor
   {
     super();                                            // call zero-argument constructor of superclass
     this.empNum=new Integer(0);                         // then set values of subclass's instance variables
     this.payRate=0;
   }
 
   public Employee(int i,String s1,String s2,int j,double d)
   {
     super(s1,s2,j);                                     // call constructor from superclass
     this.empNum=new Integer(i);                         // then set values of subclass's instance variables
     this.payRate=d;
   }
 
   public int getEmpNum()                                // accessor method, returns a primitive int
   {
     return this.empNum.intValue();                      // use intValue() method of Integer class
   }
 
   public double getPayRate()
   {
     return this.payRate;
   }
 
   public String toString()                              // over-ride toString method from Person class
   {
     return this.empNum+" "+this.firstName.trim()+" "+this.lastName.trim()+" rate: "+this.payRate;
   }
 }

DOS2d.java

/* File: DOS2d.java
 
    This program instantiates a Taxpayer object, then calculates a weekly
    tax withholding amount using the calcTax() method of the Taxpayer class.
    This program demonstrates reading records from a sequential data file.
 
    This program uses several classes that are in the java.io package. To
    help the compiler resolve these external references, the import statement
    is used. The import statement makes classes and interfaces from the
    specified package available to the compiler.
 
    The documentation of a class will tell you what package the class is in.
    Any class that is in the java.lang package is available automatically.
    You need an import statement for any class (or interface) that is in any
    package other than java.lang.
 
 */
 
 import java.io.*;                                    // import classes and interfaces from the java.io package
 
 public class DOS2d
 {
   public static void main(String[] args) throws Exception // this method throws Exception objects to its caller
   {
     int            hours;
     String         record;
     Taxpayer       subject;
     FileReader     reader;
     BufferedReader in;
 
     reader=new FileReader("Taxpayer.dat");           // specify local file name: Taxpayer.dat
     in=new BufferedReader(reader);                   // open the file so we can read its records
 
     record=in.readLine();                            // attempt to read next record
     while(record!=null)                              // execute loop if record has any characters
     {
       subject=new Taxpayer(record);                  // pass record data, instantiate taxpayer object
 
       System.out.println("Taxpayer: "+subject.getName());
       System.out.println("Pay rate: "+subject.getPayRate()+"\n");
       System.out.println("Hours worked?");
       hours=Utility.readInt();                       // ask for hours worked; keyboard input
 
       System.out.println("\n"+subject.getName()+"     taxes: "+subject.calcTax(hours));
 
       System.out.print(subject.getName()+" formatted: ");
       System.out.println(Utility.padString(subject.calcTax(hours),10,2)+"\n\n");
 
       record=in.readLine();                          // attempt to read next record
     }
 
     in.close();                                      // close the file
   }
 }

Taxpayer.java

 /* File: Taxpayer.java
 
    This class includes tax tables. It includes a calcTax() method which will
    calculate the weekly withholding tax for a taxpayer.
 
    To calculate the weekly withholding tax:
 calculate weekly gross pay:    gross=hours*payRate
 estimate annual gross pay:     annualized=gross*52
 use tax brackets to estimate annual tax
-18550 in annualized gross is taxed at 15%
-44900 marginal rate of 28%
                >44900 marginal rate of 33%
 calculate weekly withholding:  weeklyTax=annualTax/52
 */
 
 public class Taxpayer extends Employee                  // subclass the Employee class
 {
   private static final double TAXRATE1=.15;             // class variable (3 tax rates)
   private static final double TAXRATE2=.28;
   private static final double TAXRATE3=.33;
 
   private static final double TAXLIMIT1=18550;          // upper limits of tax brackets
   private static final double TAXLIMIT2=44900;
 
   public Taxpayer(String s)                             // constructor, accepts String parameter
   {
     this.empNum=new Integer(s.substring(0,5));          // extract substrings from record
                                                         //  empNum is inherited from Employee
                                                         
     this.firstName=s.substring(5,20);                   // properties inherited from NewerPerson
     this.lastName=s.substring(20,35);
     this.age=Integer.parseInt(s.substring(35,37));
     this.payRate=Double.parseDouble(s.substring(37,43));
   }
 
   public double calcTax(int hours)                      // receive one int parameter
   {
     double gross,annualized,annualTax,weeklyTax;        // declare several primitive double items
 
     gross=hours*this.payRate;                           // 1. calculate weekly gross pay
     annualized=gross*52;                                // 2. annualize it
 
     if(annualized<=Taxpayer.TAXLIMIT1)                  // 3. now handle marginal brackets
     {
       annualTax=Taxpayer.TAXRATE1*gross;                // lowest bracket, simple
     }
     else
     {
       if(annualized<=Taxpayer.TAXLIMIT2)
       {                                                 // middle bracket; use marginal rate!
         annualTax=Taxpayer.TAXRATE1*Taxpayer.TAXLIMIT1+
                   Taxpayer.TAXRATE2*(annualized-Taxpayer.TAXLIMIT1);
       }
       else
       {                                                 // highest bracket
         annualTax=Taxpayer.TAXRATE1*Taxpayer.TAXLIMIT1+
                   Taxpayer.TAXRATE2*(Taxpayer.TAXLIMIT2-Taxpayer.TAXLIMIT1)+
                   Taxpayer.TAXRATE3*(annualized-Taxpayer.TAXLIMIT2);
       }
     }
 
     weeklyTax=annualTax/52;                             // 4. calculate weekly tax
 
     return weeklyTax;                                   // return a float value
   }
 
 }

Taxpayer.dat

Taxpayer.dat (fixed-length fields)
each record consists of:
characters  0- 4: employee number
-19: first name
-34: last name
-36: age
-42: pay rate
George         Washington     54295.00
Benjamin       Franklin       61149.95

RandomNumbers.java

 /* file: RandomNumbers.java
 
    This program generates a list of random numbers without replacement. This program is a text-based
    application. It uses the user-defined RandomNumbersWithoutReplacement class, which contains all
    of the functionality one needs to get random numbers (without replacement).
     
 */
 
 public class RandomNumbers
 {
   
   public static void main(String[] args)
   {
     System.out.println();
 
     System.out.print("Enter the desired lower limit of your range of random numbers: ");
     int lower=Utility.readInt();
 
     System.out.print("                                          and the upper limit: ");
     int upper=Utility.readInt();
 
 // instantiate a (user-defined) RandomNumbersWithoutReplacement object    
     RandomNumbersWithoutReplacement list=new RandomNumbersWithoutReplacement(lower,upper);
 
 // get random numbers, one at a time
     int ran=list.next();
     while(ran>-1)
     {
       System.out.println(ran);
       ran=list.next();
     }
 
     System.out.println();
   }
 }

RandomNumbersWithoutReplacement.java

 /* file: RandomNumbersWithoutReplacement.java
 
    Re-usable class to generate a list of random numbers without replacement.
    The two steps to using this class are: 
 instantiate a RandomNumbersWithoutReplacement object. There are two options for this:
       - pass a single integer indicating the desired number of random numbers
       - pass two integers, indicating the low number and the high number in the desired range
 
       RandomNumbersWithoutReplacement list=new RandomNumbersWithoutReplacement(16);
       will set up a list of random numbers in the range 0 through 15 (16 random numbers)
 
       RandomNumbersWithoutReplacement list=new RandomNumbersWithoutReplacement(11,20);
       will set up a list of random numbers in the range 11 through 20 (10 random numbers)
 Call this class's next method to get the next random number.
       int i=list.next();
 
 */
 
 import java.util.*;                                     // the Vector class is in the java.util package
 
 public class RandomNumbersWithoutReplacement
 {
   private Vector v=new Vector();                         // instantiate a Vector object
 
   public RandomNumbersWithoutReplacement(int i)          // constructor method that receives a single int,
   {                                                      //  indicating desired number of random numbers
     this(0,i-1);                                         // call other constructor; random numbers will be in
   }                                                      //  the range 0 through i-1
 
   public RandomNumbersWithoutReplacement(int low,int high) // constructor method that receives two primitive ints
   {                                                       //  indicating beginning and ending values for the
                                                           //  random numbers
     if(high<low)                                          // do a little error checking
     {                                                     // make sure that high is not less than low
       high=low;
     }
 
     for(int j=low;j<=high;j++)                          // populate the vector with Integer objects
     {
       Integer val=new Integer(j);                       // instantiate next Integer object
       v.addElement(val);                                // add it to the vector
     }
   }
 
   public int next()                                     // method to get next random number
   {
     if(v.size()==0)                                     // if the vector is already empty,
     {                                                   //  return a -1 (all the random numbers have
       return -1;                                        //  already been used)
     }
 
     int ran=Math.floor(Math.random()*v.size());         // pick a random vector index
     Integer val=(Integer) v.elementAt(ran);             // get the Integer object from the vector
     v.removeElementAt(ran);                             // remove the element from the vector
     return val.intValue();                              // and return an int value of the Integer object
   }
 }

TriviaFileList.java

 /* File:   TriviaFileList.java
   
    This text-based application reads Trivia events from the sequential file Trivia.fil
    and displays output to the screen. Since Trivia.fil contains records with fixed-length fields,
    the String class's substring method is used to extract fields from each record.
 
    This program uses three classes from optional java packages, plus two methods from
    the user-defined Utility.java:
    - java.io.FileReader (textbook: page 672)
    - java.io.BufferedReader (textbook: page 676)
    - java.util.Date (textbook: page 586)
 
   Some methods in the Data class have been deprecated, meaning that there is a newer (and
   perhaps better) method, perhaps in some other class, that provides identical functionality.
   The nice thing about the methods from the Date class is that they are easy to use. And they
   still work -- deprecated does not mean obsolete.
   
   You will get a warning from the compiler when you use deprecated methods. This is a warning,
   not an error message.
   
 */
 
 import java.io.*;                                       // for java.io.BufferedReader and java.io.FileReader
 import java.util.*;                                     // for java.util.Date
 
 public class TriviaFileList
 {
   public static void main(String[] args)
   {
 
     Date date=new Date();                               // instantiate a Date object (some methods deprecated)
     int todayMonth=date.getMonth()+1;                   // getMonth returns 0-11 (increment by 1 for 1-12)
     int todayDay=date.getDate();                        // day of the month (1-31)
 
                                                         // generate a heading
     System.out.println("\n\nToday is " + Utility.getDayName(date.getDay()+1) + ", " +
       Utility.getMonthName(todayMonth) + " " + todayDay + ", " + (date.getYear()+1900) + "\n");
 
     System.out.println("On this day in history, the following events happened:\n");
 
     try                                                     // put I/O stuff in a try/catch block
     {
       BufferedReader in=new BufferedReader(new FileReader("Trivia.fil"));  // data file is now open
 
       String record=in.readLine();                          // attempt to read next record
       while(record!=null)                                   // execute loop if record was read
       {
         int month=Integer.parseInt(record.substring(0,2));  // extract substrings from data record
         int day=Integer.parseInt(record.substring(3,5));
         
         if(month==todayMonth && day==todayDay)              // did this event happen on current month/day?
         {
           int year=Integer.parseInt(record.substring(6,10));
 
           String event=record.substring(12);                // extract the event
           while(event.endsWith(" "))                        // strip off trailing spaces
           {
             event=event.substring(0,event.length()-1);
           }
           System.out.println(year+"  "+event);              // generate a line of output
         }
 
         record=in.readLine();                               // attempt to read next record
       }
       in.close();                                           // close the file
     }
     catch(Exception e)                                      // catch any exceptions
     {
       System.out.println("I/O exception");
       System.out.println(e.toString());
     }
 
     System.out.println();                                   // final blank line
   }
 }

Trivia.fil

Sample records from Trivia.fil (fixed-length fields)
Each record consists of:
characters:  0-1: month number of trivia event
-4: day number
-9: year number
- : trivia event
/01/1801  Giuseppe Piazzi discoved 1st asteroid, later named Ceres
/01/1801  United Kingdom of Great Britain & Ireland established
/01/1804  Haiti gains its independence
/01/1863  Emancipation Proclamation issued by Lincoln.
/01/1892  Brooklyn merges with NY to form present City of NY Ellis Island became reception center for new immig...                                         
/01/1901  Commonwealth of Australia established
/01/1902  first Rose Bowl game held in Pasadena, California.
/01/1912  first running of SF's famed "Bay to Breakers" race (7.63 miles)
/01/1934  Alcatraz officially becomes a Federal Prison.
/01/1956  Sudan gains its independence
/01/1958  European Economic Community (EEC) starts operation.
/01/1971  Cigarette advertisements banned on TV
/01/1984  AT & T broken up into 8 companies.                                                                                                                  
/01/1986  Spain & Portugal become 11th & 12th members of Common Market                                                                                        
/02/1776  first American revolutionary flag displayed.                                                                                                        
/02/1788  Georgia is 4th state to ratify US constitution                                                                                                      
/02/1893  World's Columbian Exposition opens in Chicago                                                                                                       
/02/1921  DeYoung Museum in San Francisco's Golden Gate Park opens.                                                                                           
/02/1936  first electron tube described, St Louis, Missouri                                                                                                   
/02/1959  USSR launches Mechta, 1st lunar probe & artificial in solar orbit                                                                                   
/02/1968  Dr Christian Barnard performs 1st successful heart transplant                                                                                       
/02/1972  Mariner 9 begins mapping Mars                                                                                                                       
/03/1521  Martin Luther excommunicated by Roman Catholic Church                                                                                               
/03/1777  Washington defeats British at Battle of Princeton, NJ                                                                                               
/03/1852  First Chinese arrive in Hawaii.                                                                                                                     
/03/1870  Brooklyn Bridge begun, completed on May 24, 1883                                                                                                    
/03/1888  1st drinking straw is patented.                                                                                                                     
/03/1957  first electric watch introduced, Lancaster Pennsylvania                                                                                             
/03/1959  Alaska becomes the 49th state.                                                                                                                      
/03/1977  Apple Computer incorporated.  

SampleFileWriter.java

/* File: SampleFileWriter.java
 
   This program demonstrates writing to an ASCII text file using the FileWriter
   class (textbook: page 673). This program handles exceptions that might be thrown
   to it by enclosing I/O methods in try/catch blocks.
 
   This program does not generate output to the screen (other than a potential error
   message). Get a directory listing to look for the output file (SampleFileWriter.txt),
   and use your text editor to look at the file.
 
 */
 
 import java.io.*;
 
 public class SampleFileWriter
 {
   public static void main(String[] args)
   {
     FileWriter file;
 
     try                                               // put calls to I/O methods in try/catch blocks
     {
       file=new FileWriter("SampleFileWriter.txt");
     }
     catch(Exception e)
     {
       System.out.println("Error opening file");
       return;                                         // if exception is encountered, leave the method
     }
 
     try
     {
       file.write("Hello world.\nThis is a test.\n\nThank your for your business.\n");
     }
     catch(Exception e)
     {
       System.out.println("Error writing to file");
     }
 
     try
     {
       file.close();
     }
     catch(Exception e)
     {
       System.out.println("Error closing file");
     }
   }
 }

Utility.java

/* File: Utility.java
 
    This file contains several utility methods that are designed to be used
    by other programs.
 
    readInt   - reads an int value from the keyboard
    readDouble - reads a double value from the keyboard
    readString - reads a String from the keyboard
    padString - pads a numeric string value with a designated character to form a fixed length string
    fixString - pads a string with trailing spaces to form a fixed length string
    commaString - inserts commas into a string for readability
    getMonthName - returns the name of the month
    getDayName   - returns the name of the day
    addComponent - adds a component to a container
    
 */
 
 import java.text.*;                                     // needed for DecimalFormat class
 import java.util.*;
 import java.awt.*;                                      // used by addComponent method
 
 public class Utility
 { 
 
 /************************************************************************
  readInt()
 
  Method which reads an int value from the keyboard.
 
  Parameters:
    none
 
  Returns:
    an int value
    -999999f if error (invalid input)
 
  example:
    int i=Utility.readInt();
 
 */
 
   public static int readInt()
   {
     int i;
 
     String s=Utility.readString();                      // read a String from the keyboard
 
     try
     {
       i=Integer.parseInt(s);                            // try to parse String into an int
     }
     catch(Exception e)                                  // catch exception thrown by Integer.parseInt
     {
       i=-999999;                                        // flag to indicate input error
     }
 
     return i;
   }                                                     // return value of i
 
 /************************************************************************
  readDouble()
 
  Method which reads a double value from the keyboard.
 
  Parameters:
    none
 
  Returns:
    a double value
    -999999f if error (invalid input)
 
  example:
    double d=Utility.readDouble();
 
 
 */
 
   public static double readDouble()
   {
     double d;
 
     String s=Utility.readString();                      // read a String from the keyboard
 
     try
     {
       Double doubleObject=Double.valueOf(s);            // try to parse String into a Double
       d=doubleObject.doubleValue();
     }
     catch(Exception e)                                  // catch exception
     {
       d=-999999;                                        // flag to indicate input error
     }
 
     return d;
   }                                                     // return value of f
 
 /************************************************************************
  readString()
 
  Method which reads a String value from the keyboard.
 
  Parameters:
    none
 
  Returns:
    a String object
 
  example:
    String inString=Utility.readString();
 
 */
 
   public static String readString()
   {
     int    input=0;                                     // define and initialize an int variable
     String s="";                                        // define and initialize a String object
 
     while(input!=10)                                    // loop until LF byte is read
     {
       try
       {
         input=System.in.read();                         // read next byte from keyboard
       }
       catch(Exception e)
       {
         input=13;
       }
       if(input!=13 && input!=10)                        // if byte is not CR and not LF, concatenate
       {
         s=s+(char)input;                                // cast int input as char, then concatenate
       }
     }
     return s;                                           // return String to calling program
   }
 
 
 /************************************************************************
  padString(Number,int,int,String)
 
  Method which pads a string of digits with trailing zeroes and a specified
  leading padding character to form a fixed length string with
  optional decimal places.
 
  Parameters:
    Number number           input Number object
    int    chars            length of desired fixed length string
    int    decimals         desired number of digits to the right of the decimal point
                                  in returned fixed length string
    String lead             character to be used for leading padding
 
  Returns:
    a String object
 
  example:
    String output=Utility.padString(50.4,6,2,"*");
 
    output will have a String value of "*50.40"
 
 */
 
   public static String padString(Number number,int chars,int decimals,String lead)
   {
     DecimalFormat format;
     String        s="";
 
     if(decimals>0)
     {
       s=".";
       for(int i=0;i<decimals;i++)
       {
         s=s+"0";
       }
     }
 
     int digits=chars-s.length();
     for(int i=0;i<digits;i++)
     {
       if(i>0 && i%3==0)
       {
         s=","+s;
       }
       s="#"+s;
     }
 
     format=new DecimalFormat(s);
     s=format.format(number);
     digits=chars-s.length();
     for(int i=0;i<digits;i++)
     {
       s=lead+s;
     }
     return s;
   }
 
   public static String padString(long number,int chars,int decimals,String lead)
   {
     return Utility.padString(new Long(number),chars,decimals,lead);
   }
 
   public static String padString(double number,int chars,int decimals,String lead)
   {
     return Utility.padString(new Double(number),chars,decimals,lead);
   }
 
   public static String padString(String number,int chars,int decimals,String lead)
   {
     return Utility.padString(new Double(number),chars,decimals,lead);
   }
 
   public static String padString(Number number,int chars,int decimals)
   {
     return Utility.padString(number,chars,decimals," ");
   }
 
   public static String padString(long number,int chars,int decimals)
   {
     return Utility.padString(new Long(number),chars,decimals," ");
   }
 
   public static String padString(double number,int chars,int decimals)
   {
     return Utility.padString(new Double(number),chars,decimals," ");
   }
 
   public static String padString(String number,int chars,int decimals)
   {
     return Utility.padString(new Double(number),chars,decimals," ");
   }
 
   public static String padString(Number number,int chars)
   {
     return Utility.padString(number,chars,0," ");
   }
 
   public static String padString(long number,int chars)
   {
     return Utility.padString(new Long(number),chars,0," ");
   }
 
   public static String padString(double number,int chars)
   {
     return Utility.padString(new Double(number),chars,0," ");
   }
 
   public static String padString(String number,int chars)
   {
     return Utility.padString(new Double(number),chars,0," ");
   }
 
   public static String padString(Number number,int chars,String lead)
   {
     return Utility.padString(number,chars,0,lead);
   }
 
   public static String padString(long number,int chars,String lead)
   {
     return Utility.padString(new Long(number),chars,0,lead);
   }
 
   public static String padString(double number,int chars,String lead)
   {
     return Utility.padString(new Double(number),chars,0,lead);
   }
 
   public static String padString(String number,int chars,String lead)
   {
     return Utility.padString(new Double(number),chars,0,lead);
   }
 
 /************************************************************************
  fixString(String,int)
 
  Method which pads a string with trailing spaces to form a fixed length field.
 
  Parameters:
    String inString         input string of digits
    int    chars            length of desired fixed length string
 
  Returns:
    a String object
 
  example:
    input="test";
    output=Utility.fixString(input,10);
 
 
    output will have a String value of "test      "
 */
 
   public static String fixString(String inString,int chars)
   {
     String s=inString;                                  // get temp string
     for(int i=0;i<chars-inString.length();i++)          // add trailing spaces
     {
       s=s+" ";
     }
     return s.substring(0,chars);                        // return fixed length field
   }
 
 /************************************************************************
  commaString(String,int)
 
  Method which inserts commas into a number for readability
 
  Parameters:
    String inString         input string of digits
    int    chars            length of desired fixed length string
 
  Returns:
    a String object
 
  example:
    input="test";
    output=Utility.fixString(input,10);
 
 
    output will have a String value of "test      "
 */
 
   public static String commaString(String inString)
   {
     String s="";
     int decimal=inString.indexOf(".");
     if(decimal==-1)
     {
       if(inString.length()<3)
       {
         return inString;
       }
       s=inString.substring(inString.length()-3,inString.length());
       inString=inString.substring(0,inString.length()-3);
       while(inString.length()>2)
       {
         if(inString.length()==3)
         {
           s=inString+","+s;
           inString="";
         }
         else
         {
           s=inString.substring(inString.length()-3,inString.length())+","+s;
           inString=inString.substring(0,inString.length()-3);
         }
       }
       if(inString.length()>0)
       {
         s=inString+","+s;
       }
     }
     return s;
   }
 
   public static String commaString(long number)
   {
     return Utility.commaString(number+"");
   }
 
   public static String commaString(double number)
   {
     return Utility.commaString(number+"");
   }
 
 /************************************************************************
  getMonthName(int)
 
  Returns the month name of a desired month.
  
  Parameters:
    int    monthNumber      month number (1-12)
 
  Returns:
    a String object
 
  example:
    String monthName=Utility.getMonthName(7);
 
 */
 
   public static String getMonthName(int monthNumber)
   {
     String[] monthNames=new String[12];
     monthNames[0]="January";
     monthNames[1]="February";
     monthNames[2]="March";
     monthNames[3]="April";
     monthNames[4]="May";
     monthNames[5]="June";
     monthNames[6]="July";
     monthNames[7]="August";
     monthNames[8]="September";
     monthNames[9]="October";
     monthNames[10]="November";
     monthNames[11]="December";
     
     return monthNames[monthNumber-1];
   }
 
 /************************************************************************
  getDayName(int)
 
  Returns the day name of a desired day number.
  
  Parameters:
    int    dayNumber      day number (1-7)
 
  Returns:
    a String object
 
  example:
    String dayName=Utility.getDayName(7);
 
 */
 
   public static String getDayName(int dayNumber)
   {
     String[] dayNames=new String[7];
     dayNames[0]="Sunday";
     dayNames[1]="Monday";
     dayNames[2]="Tuesday";
     dayNames[3]="Wednesday";
     dayNames[4]="Thursday";
     dayNames[5]="Friday";
     dayNames[6]="Saturday";
     
     return dayNames[dayNumber-1];
   }
 
 /************************************************************************
  addComponent(Container container,Component component,int align)
 
 
  Method which adds a component to a container. This method will use a components
  preferred size, not necessarily filling up the container (as GridLayout would do).
 
  Parameters:
    Container container      the container to which the component is to be added
    Component component      the component
    int       align          a constant from the FlowLayout class
 
  Returns:
    nothing
 
  example:
 
    Panel myPanel=new Panel();
    myPanel.setLayout(new GridLayout(4,2));
 
    Button myButton=new Button("click me");
 
    Utility.addComponent(myPanel,myButton);
 
 */
 
   public static void addComponent(Container container,Component component,int align)
   {
     Panel tempPanel=new Panel();
     tempPanel.setLayout(new FlowLayout(align));
     tempPanel.add(component);
     container.add(tempPanel);
   }
 
   public static void addComponent(Container container,Component component)
   {
     addComponent(container,component,FlowLayout.LEFT);
   }
 
 }

GUI1.java

/* File: GUI1.java
 
    This is a JFrame-based (GUI) Java application.
 
    GUI1 sub-classes (extends) the Java class hierarchy, defining a new class
    that is a sub-class (child) of the JFrame class.
 
    The class hierarchy, from top to GUI1, consists of the following classes:
 
      java.lang.Object
         |--java.awt.Component
            |--java.awt.Container
               |--java.awt.Window
                  |--java.awt.Frame
                     |--javax.swing.JFrame
                        |--GUI1
 
    The corresponding class declarations for the classes shown in this
    hierarchy include:
      class Object
      class Component extends Object
      class Container extends Component
      class Window extends Container
      class Frame extends Window
      class JFrame extends Frame
      class GUI1 extends JFrame
 
    GUI1 inherits methods and properties from its super-classes. It also
    uses classes that are available in the java.awt and javax.swing packages.
 
    Inherited methods used by GUI1:
    - setSize()          inherited from the Component class
    - setTitle()         inherited from the Frame class
    - setVisible()       inherited from the Component class
 
 */
 
 import javax.swing.*;
 
 public class GUI1 extends JFrame                        // sub-class the JFrame class
 {
   public static void main(String[] args)                // main() method; execution starts here
   {
     new GUI1();                                         // instantiate a GUI1 object (call its constructor)
   }
 
   public GUI1()                                         // constructor for the GUI1 class
   {
     JTextArea display;                                  // define a JTextArea object (from javax.swing package)
 
     this.setTitle("Title for GUI1");                    // setTitle() is inherited from superclass
     this.setSize(400,600);                              //  as is setSize(); operate on current GUI1 object
 
     display=new JTextArea();                            // instantiate a JTextArea object
     this.add(display);                                  // add the object to the current GUI1 object
 
     this.setVisible(true);                              // switch to GUI and display frame
 
     for(int i=1;i<=10;i++)
     {
       display.append(i+"\n");                           // append string to display object
     }
   }
 }

GUI2a.java

/* File: GUI2a.java
 
    GUI2a demonstrates the use of a layout manager to arrange (and maintain
    the arrangement of) widgets on the screen. Java has several Layout Managers:
      - FlowLayout
      - GridLayout
      - BorderLayout
      - GridBagLayout
 
    This program uses the FlowLayout layout manager.
 
    GUI2a demonstrates placing several GUI components (widgets) on the screen
    (into a frame). It demonstrates the use of three different widgets,
    each of which is a class defined in the javax.swing package:
    - JLabel
    - JTextField
    - JButton
 
    GUI2a demonstrates event-driven programming by responding to a button click
    in the program. The program implements the ActionListener interface by defining
    an actionPerformed() method. The ActionListener interface has one abstract method:
    actionPerformed. To implement an interface, you must provide a definition for each
    of the interfaces abstract methods.
 
    Java uses a delegation-based event-handling model. You can place various Event Sources
    on your layout (GUI application). Most components (JButtons, JTextFields, etc)
    can be Event Sources. You then register an Event Listener for each Event Source.
    An Event Listener is anything that implements one of the Listener interfaces.
    In this example, for instance, GUI2a implements ActionListener, so GUI2a "is a"
    ActionListener. It can, therefore, be used as an ActionListener, registered to
    listen for events on an Event Source.
 
    To incorporate event-handling in your program, you need to do four things:
 import classes and interfaces from the awt.event package
 include "implements ActionListener" in your class declaration (so that your class
       "is a" ActionListener)
 actually implement the ActionListener interface -- over-ride the actionPerformed() method
 register an Event Listener for any desired Event Source
 
 */
 
 import java.awt.event.*;                                // for the ActionListener interface
 import java.awt.*;                                      // for the layout managers
 import javax.swing.*;                                   // for the GUI swing components
 
 public class GUI2a extends JFrame implements ActionListener
 {
   private JTextField startText,stopText,sumText;
   private JButton    calcButton,doneButton;
 
   public static void main(String[] args)
   {
     new GUI2a();                                        // instantiate a GUI2a object
   }
 
   public GUI2a()                                        // the constructor for the GUI2a class
   {
     this.setLayout(new FlowLayout());                   // set "this" GUI2a's layout manager to FlowLayout
 
     this.setTitle("Title for GUI2a");                   // setTitle of "this" GUI2a object
     this.setSize(600,350);
 
     this.add(new JLabel("starting value:"));            // add a JLabel object to the frame
 
     startText=new JTextField(10);                       // instantiate a JTextField object
     this.add(startText);                                // add to frame
 
     this.add(new JLabel("ending value:"));              // add another JLabel object
 
     stopText=new JTextField(10);                        // and another JTextField object
     this.add(stopText);
 
     this.add(new JLabel("sum:"));                       // another JLabel object
 
     sumText=new JTextField(10);                         // another JTextField object
     sumText.setEditable(false);                         // use method to prevent editing of this object
     this.add(sumText);
 
     calcButton=new JButton("Calculate");                // instantiate JButton object
     calcButton.addActionListener(this);                 // register this GUI2a object as Event Listener
                                                         //   for calcButton (Event Source)
     this.add(calcButton);
 
     doneButton=new JButton("Quit");                     // another button
     doneButton.addActionListener(this);                 // register Event Listener for this Event Source
     this.add(doneButton);
 
     this.setVisible(true);                              // make frame visible
   }
 
   public void actionPerformed(ActionEvent e)            // event-handling method, receives ActionEvent object
   {
     if(e.getSource()==this.calcButton)                  // check source of event that occurred
     {                                                   //  was it calcButton?
       int start,stop,sum;                               // define three int variables
 
       start=Integer.parseInt(startText.getText());      // convert startText value to int
       stop =Integer.parseInt(stopText.getText());
       sum=0;                                            // initialize sum
 
       for(int i=start;i<=stop;i++)                      // loop to calculate sum
       {
         sum=sum+i;
       }
 
       sumText.setText(Integer.toString(sum));           // set text of sumText TextField object for display
     }
 
     if(e.getSource()==doneButton)                       // was event caused by doneButton?
     {
       System.exit(0);                                   // quit program
     }
   }
 }

GUI2b.java

/* File: GUI2b.java
 
    GUI2b uses the GridLayout Layout Manager. It reads events from Trivia.fil and displays
    today's Trivia events in a JTextArea (it uses the Date class to get the current date).
    Since Trivia.fil contains records with fixed-length fields, the program uses the String
    class's substring() method to extract individual fields from the records.
 
    This program also implements an additional event listener, WindowListener. The WindowListener
    interface includes seven methods. To implement this interface, you must over-ride all seven of
    these methods. This program is actually interested in only one of the methods, windowClosing.
    This program provides code for when the user clicks on the little X in the top right corner of
    the window to close the window.
 
 */
 
 import java.awt.*;                                      // for the layout managers
 import java.awt.event.*;                                // for the listener interfaces
 import javax.swing.*;                                   // for the GUI swing components
 import java.util.*;                                     // for the Date class
 import java.io.*;                                       // for the I/O classes
 
 public class GUI2b extends JFrame implements ActionListener,WindowListener
 {
   private JButton    triviaButton,clearButton,quitButton;  // define three JButton objects
   private JTextArea display;                               // and a JTextArea for output
 
   public static void main(String[] args)
   {
     new GUI2b();
   }
 
   public GUI2b()
   {
     this.setTitle("Title for GUI2b");
     this.setSize(600,350);
 
     this.setLayout(new GridLayout(2,1));                // set layout manager of the GUI2b
                                                         //  object to GridLayout (2 rows, 1 column)
 
     Panel topPanel=new Panel();                         // instantiate a Panel (container) to hold
                                                         //  three buttons for the top of the GridLayout
     topPanel.setLayout(new GridLayout(1,3));            // set the Panel's layout manager
                                                         
     
     triviaButton=new JButton("Show Trivia");            // instantiate JButton object
     triviaButton.addActionListener(this);               // register Event Listener
     topPanel.add(triviaButton);                         // add button to Panel container
 
     clearButton=new JButton("Clear");
     clearButton.addActionListener(this);
     topPanel.add(clearButton);
 
     quitButton=new JButton("Quit");
     quitButton.addActionListener(this);
     topPanel.add(quitButton);
 
     this.add(topPanel);                                 // add Panel to the Frame
     
     display=new JTextArea();                            // instantiate JTextArea object
     display.setEditable(false);                         // prevent user editing of the TextArea
     this.add(display);                                  // add textArea to Frame
     
     this.addWindowListener(this);                       // register WindowListener
     
     this.setVisible(true);
   }
 
   public void actionPerformed(ActionEvent e)            // event-handling method, receives ActionEvent object
   {
     if(e.getSource()==this.triviaButton)                // check source of event that occurred
     {                                                   //  was it the triviaButton Button object?
 
       Date date=new Date();                             // instantiate a Date object (deprecated)
       int todayMonth=date.getMonth()+1;                 // getMonth returns 0-11 (increment by 1)
       int todayDay=date.getDate();                      // day of the month (1-31)
       int listCount=0;                                  // initialize a counter
                                                         // initialize a string
       String string="On "+todayMonth+"/"+todayDay+", the following events happened:\n";
 
       try                                                 // put I/O stuff in a try/catch block
       {
         BufferedReader in=new BufferedReader(new FileReader("Trivia.fil"));  // data file is now open
 
         String record=in.readLine();                      // attempt to read next record
         while(record!=null)                               // execute loop if record was read
         {
           int thisMonth=Integer.parseInt(record.substring(0,2));  // extract month and day from record
           int thisDay=Integer.parseInt(record.substring(3,5));    // convert from String to int
         
           if(todayMonth==thisMonth && todayDay==thisDay)  // is this trivia event for today?
           {
             string=string+record.substring(6,10)+"\t"+record.substring(12)+"\n";
             listCount++;
           }
         
           record=in.readLine();                           // attempt to read next record
         }
         in.close();                                       // close the file
       
       }
       catch(Exception ex)                                 // catch any exceptions
       {
         display.setText("error attempting to process Trivia.fil\n"+ex.toString());
         return;
       }
 
       string=string+"\n"+listCount+" trivia events listed\n";
       display.setText(string);    
     }
 
     if(e.getSource()==this.clearButton)                 // was event caused by clearButton?
     {
       display.setText("");                              // clear the textArea
     }
 
     if(e.getSource()==this.quitButton)                  // was event caused by quitButton?
     {
       System.exit(0);                                   // quit program
     }
   }
 
   public void windowActivated(WindowEvent e)            // define WindowListener's seven abstract methods
   {
   }
   public void windowClosed(WindowEvent e)
   {
   }
   public void windowClosing(WindowEvent e)
   {
     System.exit(0);
   }
   public void windowDeactivated(WindowEvent e)
   {
   }
   public void windowDeiconified(WindowEvent e)
   {
   }
   public void windowIconified(WindowEvent e)
   {
   }
   public void windowOpened(WindowEvent e)
   {
   }
 
 }

GUI2c.java

/* File: GUI2c.java
 
    GUI2c uses BorderLayout as the Layout Manager. It provides a JTextField, into which
    the user can enter a customer number (it responds to pressing Enter in the textfield).
    The program reads the records in Customer.dat to find the matching customer, and displays
    customer information in a JTextArea.
    
    Since Customer.dat contains variable-length, delimited fields, this program uses the
    String class's split method to split the records apart into their fields.
 
    This program uses a Panel object as a sub-Container. The Panel may have its own
    Layout Manager. You may add Components to the Panel, then add the Panel to your
    Frame.
 
 */
 
 import java.awt.*;
 import java.awt.event.*;
 import javax.swing.*;
 import java.io.*;
 
 public class GUI2c extends JFrame implements ActionListener
 {
   private JTextField custNumText;
   private JTextArea  display;
   private JButton    quitButton;
 
   public static void main(String[] args)
   {
     new GUI2c();
   }
 
   public GUI2c()
   {
     this.setTitle("Title for GUI2c");
     this.setSize(600,350);
 
     this.setLayout(new BorderLayout());                 // set Frame's Layout Manager
 
     Panel topPanel=new Panel();                         // instantiate a Panel object (container)
     
     topPanel.add(new JLabel("Customer number: "));      // instantiate a JLabel object and add
                                                         //  it to the panel
 
     custNumText=new JTextField(10);                     // instantiate a JTextField for input
     custNumText.addActionListener(this);                // respond to Enter in textfield
     topPanel.add(custNumText);
     
     this.add(topPanel,BorderLayout.NORTH);              // add Panel to top of Frame
 
     display=new JTextArea();                            // instantiate JTextArea for output
     this.add(display,BorderLayout.CENTER);              // add textArea to center of Frame
 
     quitButton=new JButton("Quit");                     // instantiate a JButton
     quitButton.addActionListener(this);                 // respond to button click
     this.add(quitButton,BorderLayout.SOUTH);            // add to bottom of frame
 
     this.setVisible(true);
   }
 
   public void actionPerformed(ActionEvent e)
   {
     if(e.getSource()==this.custNumText)                 // was textfield the event source?
     {
       try                                               // put I/O stuff in a try/catch block
       {                                                 // get customer number from textfield
         int customerNumber=Integer.parseInt(this.custNumText.getText());
         boolean flag=false;                             // set a flag to false
         
         BufferedReader in=new BufferedReader(new FileReader("Customer.dat"));  // open data file
 
         String record=in.readLine();                    // attempt to read next record
         while(record!=null)                             // execute loop if record was read
         {
           String[] fields=record.split("\t");           // split record apart based on delimiter
           int thisNumber=Integer.parseInt(fields[0]);   // convert first field to int
                   
           if(customerNumber==thisNumber)                // is this the desired customer?
           {
             display.setText(fields[0]+"\n"+fields[1]+", "+fields[2]+"\n"+fields[4]+
"/"+fields[5]+"/"+fields[3]+"\n$"+fields[6]);
             flag=true;                                  // set flag to true
             break;                                      // and break out of loop
           }
         
           record=in.readLine();                           // attempt to read next record
         }
         in.close();                                       // close the file
       
         if(!flag)                                         // if flag is still false,
         {                                                 //  customer not found
           display.setText("Customer not found");
         }
 
       }
       catch(Exception ex)                                 // catch any exceptions
       {
         display.setText("error attempting to process Customer.dat\n"+ex.toString());
         return;
       }
       
     }
 
     if(e.getSource()==this.quitButton)                    // quit button
     {
       System.exit(0);
     }
 
   }
 }

Customer.dat

Sample records from Customer.dat (variable-length, tab-delimited records)
each record consists of: 
customer number, tab, last name, tab, first name, tab, year, tab, month, tab, day, tab, account balance
	Clark	Pamela	1986	3	1	179
	Harris	Rachel	1986	3	1	415
	Pittman	Lagatha	1986	3	1	940
	Medders	Barbara	1986	3	1	2175
	Prince	Leola	1986	3	1	837
	Coggins	Sharon	1986	3	1	3960
	Ray	Tracie O.	1986	3	1	1850
	Thompson	Nettie	1986	3	1	860
	Hughes	Beverly A.	1986	3	1	1640
	Isbell	Linda Jean	1986	3	1	1176
	Mason	Ollie Bell	1986	3	1	4462
	Richardson	Jayne	1986	3	1	1280
	Buchanan	Mary	1986	3	1	2000
	Carr	Linda	1986	3	1	400
	Copeland	Charlotte	1986	3	1	1050
	Davis	Catherine	1986	3	1	3280
	Foster	Linda J.	1986	3	1	2400
	Jackson	Mary A	1986	3	1	3270
	Pippin	Bonnie	1986	3	1	4400
	Stewart	Shirley	1986	3	1	3500
	Banks	Marie	1986	3	1	3829
	Clark	Janet Marie	1986	3	1	2450
	Bishop	Bertha	1986	3	1	1561
	Pennington	Deborah	1986	3	1	3772
	Bright	Linda	1986	3	1	4000
	Williams	Vanessa J.	1986	3	1	3200
	West	Wanda L.	1986	3	1	3000
	Houston	Bessie Mae	1986	3	1	4987
	Baker	Mary E.	1986	3	1	250
	Gandy	Wilda Q.	1986	4	1	1050
	Ward	Barbara	1986	4	1	1750
	Lucious	Mary	1986	4	1	50
	Lyons	Allie V.	1986	4	1	2572
	Sorrell	Valerie Kay	1986	5	1	250
	Park	Kangsook	1986	5	1	2140
	McDavitt	Pam	1986	5	1	1400
	Roy	Mary B.	1986	6	1	250

GUI3a.java

 /* File: GUI3a.java
 
 This program demonstrates JScrollBar, AdjustmentListener, and Color objects.
 It also demonstrates the concept of an "Adapter class" -- WindowAdapter.
 Adapter classes provide an alternative to implementing an interface, subclass the
 Adapter class instead.
 
 */
 
 import java.awt.*;
 import java.awt.event.*;
 import javax.swing.*;
 
 // the AdjustmentListener interface listens for sliding of a JScrollBar
 public class GUI3a extends JFrame implements AdjustmentListener
 {
   private JScrollBar redScroll,greenScroll,blueScroll;
   private JLabel redLabel,greenLabel,blueLabel;
   private JTextArea display;
   
   public static void main(String[] args)
   {
     new GUI3a();
   }
 
   public GUI3a()
   {
     this.setTitle("Title for GUI3a");
     this.setSize(600,350);
 
     this.setLayout(new GridLayout(1,2));                // the application uses GridLayout, 1 row, 2 columns
 
     Panel leftPanel=new Panel();                        // a Panel to hold components for the left cell
     leftPanel.setLayout(new GridLayout(3,1));           // left panel will be 3 rows, 1 column
     
     Panel redPanel=new Panel();                         // contents for the first cell in leftPanel
     redPanel.setLayout(new GridLayout(1,2));
     redPanel.setBackground(Color.RED);                  // set background color of this panel to red
 
     redScroll=new JScrollBar(JScrollBar.HORIZONTAL,128,1,0,256);  // instantiate a JScrollBar
     redScroll.addAdjustmentListener(this);              // register adjustmentListener
 
     redLabel=new JLabel("  128");                       // instantiate JLabel
     redLabel.setForeground(Color.WHITE);                // set its text color to white
 
     redPanel.add(redScroll);                            // add scrollbar to redPanel
     redPanel.add(redLabel);                             // add label to redPanel
     leftPanel.add(redPanel);                            // add redPanel to leftPanel
     
     Panel greenPanel=new Panel();                       // the greenPanel
     greenPanel.setLayout(new GridLayout(1,2));
     greenPanel.setBackground(Color.GREEN);
 
     greenScroll=new JScrollBar(JScrollBar.HORIZONTAL,128,1,0,256);
     greenScroll.addAdjustmentListener(this);
 
     greenLabel=new JLabel("  128");
     greenLabel.setForeground(Color.BLACK);
 
     greenPanel.add(greenScroll);
     greenPanel.add(greenLabel);
     leftPanel.add(greenPanel);                          // add greenPanel to leftPanel
     
     Panel bluePanel=new Panel();                        // the bluePanel
     bluePanel.setLayout(new GridLayout(1,2));
     bluePanel.setBackground(Color.BLUE);
 
     blueScroll=new JScrollBar(JScrollBar.HORIZONTAL,128,1,0,256);
     blueScroll.addAdjustmentListener(this);
 
     blueLabel=new JLabel("  128");
     blueLabel.setForeground(Color.WHITE);
 
     bluePanel.add(blueScroll);
     bluePanel.add(blueLabel);
     leftPanel.add(bluePanel);                           // add bluePanel to leftPanel
     
     this.add(leftPanel);                                // add the left panel to the overall GridLayout
     
     display=new JTextArea();                            // JTextArea for right side of GUI3a
     display.setBackground(new Color(128,128,128));      // set to medium gray
     this.add(display);                                  // add textarea to overall GridLayout
 
     this.addWindowListener(new MyWindowListener());     // instantiate a MyWindowListener object,
                                                         // register it as a Window Listener
     this.setVisible(true);
 
   }
 
   public void adjustmentValueChanged(AdjustmentEvent e) // respond to sliding any scrollbar
   {
     int red=redScroll.getValue();                       // get current "value" of each scrollbar
     int green=greenScroll.getValue();
     int blue=blueScroll.getValue();
     
     display.setBackground(new Color(red,green,blue));   // update backgroundcolor of textarea
     
     redLabel.setText("  "+red);                           // display current value of each scrollbar
     greenLabel.setText("  "+green);                       //  on its corresponding label
     blueLabel.setText("  "+blue);
   }
 
   class MyWindowListener extends WindowAdapter          // named inner class, extends WindowAdapter
   {
     public void windowClosing(WindowEvent e)            // over-ride the windowClosing event
     {
       System.exit(0);
     }
   }
 
 }

GUI3b.java

/* File: GUI3b.java
 
 This program uses NO Layout Manager: null.
 
 */
 
 import java.awt.*;
 import java.awt.event.*;
 import javax.swing.*;
 
 // the AdjustmentListener interface listens for sliding of a JScrollBar
 public class GUI3b extends JFrame implements AdjustmentListener
 {
   private JScrollBar redScroll,greenScroll,blueScroll;
   private JLabel redLabel,greenLabel,blueLabel;
   private JTextArea display;
   
   public static void main(String[] args)
   {
     new GUI3b();
   }
 
   public GUI3b()
   {
     this.setTitle("Title for GUI3b");
     this.setSize(600,350);
 
     this.setLayout(null);                               // explicitly state NO Layout Manager
 
     int left=10;
     int top=10;
     int width=250;
     int height=100;
     
     Panel redPanel=new Panel();                         // contents for the first cell in leftPanel
     redPanel.setLayout(null);                           // no Layout Manager for panel as well
     redPanel.setSize(width,height);                     // manually set the panel's size
     redPanel.setLocation(left,top);                     // and location
     redPanel.setBackground(Color.RED);                  // set background color of this panel to red
 
     redScroll=new JScrollBar(JScrollBar.HORIZONTAL,128,1,0,256);  // instantiate a JScrollBar
     redScroll.setSize(width-20,height/2);               // set its size
     redScroll.setLocation(10,10);                       //  and location (within redPanel)
     redScroll.addAdjustmentListener(this);              // register adjustmentListener
 
     redLabel=new JLabel("128",SwingConstants.CENTER);   // instantiate JLabel
     redLabel.setSize(width-20,20);
     redLabel.setLocation(10,height/2+10);
     redLabel.setForeground(Color.WHITE);                // set its text color to white
 
     redPanel.add(redScroll);                            // add scrollbar to redPanel
     redPanel.add(redLabel);                             // add label to redPanel
     this.add(redPanel);                                 // add redPanel directly to application
     
     Panel greenPanel=new Panel();                       // the greenPanel
     greenPanel.setLayout(null);
     greenPanel.setSize(width,height);
     greenPanel.setLocation(left,top+height+10);
     greenPanel.setBackground(Color.GREEN);
 
     greenScroll=new JScrollBar(JScrollBar.HORIZONTAL,128,1,0,256);
     greenScroll.setSize(redScroll.getSize().width,redScroll.getSize().height);
     greenScroll.setLocation(redScroll.getLocation().x,redScroll.getLocation().y);
     greenScroll.addAdjustmentListener(this);
 
     greenLabel=new JLabel("128",SwingConstants.CENTER);
     greenLabel.setSize(redLabel.getSize().width,redLabel.getSize().height);
     greenLabel.setLocation(redLabel.getLocation().x,redLabel.getLocation().y);
     greenLabel.setForeground(Color.BLACK);
 
     greenPanel.add(greenScroll);
     greenPanel.add(greenLabel);
     this.add(greenPanel);
     
     Panel bluePanel=new Panel();                        // the bluePanel
     bluePanel.setLayout(null);
     bluePanel.setSize(width,height);
     bluePanel.setLocation(left,top+2*(height+10));
     bluePanel.setBackground(Color.BLUE);
 
     blueScroll=new JScrollBar(JScrollBar.HORIZONTAL,128,1,0,256);
     blueScroll.setSize(redScroll.getSize().width,redScroll.getSize().height);
     blueScroll.setLocation(redScroll.getLocation().x,redScroll.getLocation().y);
     blueScroll.addAdjustmentListener(this);
 
     blueLabel=new JLabel("128",SwingConstants.CENTER);
     blueLabel.setSize(redLabel.getSize().width,redLabel.getSize().height);
     blueLabel.setLocation(redLabel.getLocation().x,redLabel.getLocation().y);
     blueLabel.setForeground(Color.WHITE);
 
     bluePanel.add(blueScroll);
     bluePanel.add(blueLabel);
     this.add(bluePanel);
     
     display=new JTextArea();                            // JTextArea for right side of GUI3a
     display.setSize(250,320);
     display.setLocation(340,10);
     display.setBackground(new Color(128,128,128));      // set to medium gray
     this.add(display);
 
     this.addWindowListener(new MyWindowListener());     // instantiate a MyWindowListener object,
                                                         // register it as a Window Listener
 
     this.setVisible(true);
 
   }
 
   public void adjustmentValueChanged(AdjustmentEvent e) // respond to sliding any scrollbar
   {
     int red=redScroll.getValue();                       // get current "value" of each scrollbar
     int green=greenScroll.getValue();
     int blue=blueScroll.getValue();
     
     display.setBackground(new Color(red,green,blue));   // update backgroundcolor of textarea
     
     redLabel.setText(""+red);                           // display current value of each scrollbar
     greenLabel.setText(""+green);                       //  on its corresponding label
     blueLabel.setText(""+blue);
   }
 
   class MyWindowListener extends WindowAdapter          // named inner class, extends WindowAdapter
   {
     public void windowClosing(WindowEvent e)            // over-ride the windowClosing event
     {
       System.exit(0);
     }
   }
 
 }

GUI4a.java

/* File: GUI4a.java
 
    GUI4a modifies GUI3b, using a menu bar instead of buttons.
 
 */
 
 import java.awt.*;
 import java.awt.event.*;
 import javax.swing.*;
 
 
 public class GUI4a extends JFrame implements ActionListener
 {
   private JMenuItem  calculateItem,clearItem,exitItem;   // three menu items (to be clicked)
   private JTextField startText,stopText,sumText;
   private JTextArea  displayArea;
   
   public static void main(String[] args)
   {
     new GUI4a();
   }
 
   public GUI4a()
   {
     JMenuBar menuBar=new JMenuBar();                    // instantiate a JMenuBar object
     this.setJMenuBar(menuBar);                           // add it to the frame
     
     JMenu fileMenu=new JMenu("File");                   // first main menu option
 
     calculateItem=new JMenuItem("Calculate");           // instantiate item for the menu option
     fileMenu.add(calculateItem);                        // and add it to the menu option
     calculateItem.addActionListener(this);              // register event listener for menu item
 
     clearItem=new JMenuItem("Clear");
     fileMenu.add(clearItem);
     clearItem.addActionListener(this);
 
     exitItem=new JMenuItem("Exit");
     fileMenu.add(exitItem);
     exitItem.addActionListener(this);
 
     menuBar.add(fileMenu);                              // add the menu option to the menubar
 
     this.setTitle("Title for GUI4a");
     this.setSize(600,350);
 
     this.setLayout(new BorderLayout());                 // set layout manager of the frame to BorderLayout
 
     JPanel topPanel=new JPanel();
     topPanel.setLayout(new GridLayout(3,2));
 
     Utility.addComponent(topPanel,new Label("starting value:"),FlowLayout.RIGHT);
 
     startText=new JTextField(10);
     Utility.addComponent(topPanel,startText);
 
     Utility.addComponent(topPanel,new Label("ending value:"),FlowLayout.RIGHT);
 
     stopText=new JTextField(10);
     Utility.addComponent(topPanel,stopText);
 
     Utility.addComponent(topPanel,new Label("sum:"),FlowLayout.RIGHT);
 
     sumText=new JTextField(10);
     sumText.setEditable(false);
     Utility.addComponent(topPanel,sumText);
 
     this.add(topPanel,BorderLayout.NORTH);
 
     displayArea=new JTextArea();                        // instantiate a JTextArea, and put it in a JScrollPane
     JScrollPane scroll=new JScrollPane(displayArea,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
     this.add(scroll,BorderLayout.CENTER);               // add the JScrollPane to the center region
     
     this.addWindowListener(new MyWindowListener());
 
     this.setVisible(true);
 
   }
 
   public void actionPerformed(ActionEvent e)
   {                                                     // instead of calling e.getSource three times
     JMenuItem thisItem=(JMenuItem) e.getSource();       // call it once, and save its returned value
                                                         // (must cast Object object as MenuItem object)
 
     if(thisItem==this.calculateItem)                    // determine which menu item was clicked
     {
       float start,stop,sum;
 
       try                                               // put Exception-throwing code in try block
       {
         start=Float.valueOf(startText.getText()).floatValue();
         stop =Float.valueOf(stopText.getText()).floatValue();
       }
       catch(Exception ex)                               // catch any possible Exceptions from try block
       {
         displayArea.append("invalid input!\n");
         return;                                         // return after handling Exception
       }
 
       sum=0f;
       displayArea.setText("");                          // clear displayArea (note null string, not " ")
   
       for(float f=start;f<=stop;f++)
       {
         displayArea.append(f+"\n");
         sum=sum+f;
       }
 
       sumText.setText(Float.toString(sum));
     }
 
     if(thisItem==this.clearItem)                        // clear item; reset text components
     {
       startText.setText("");
       stopText.setText("");
       sumText.setText("");
       displayArea.setText("");
     }
 
     if(thisItem==this.exitItem)                         // exit item; terminate program
     {
       System.exit(0);
     }
   }
 
   class MyWindowListener extends WindowAdapter          // named inner class, extends WindowAdapter
   {
     public void windowClosing(WindowEvent e)            // over-ride the windowClosing event
     {
       System.exit(0);
     }
   }
 
 }

Threader.java

/* File: Threader.java
 
    This GUI application demonstrates multi-threaded programming. To use a Thread in a Java program,
    you need to subclass the Thread class, over-riding the run() method to provide functionality
    to your thread. In this program: instantiate your subclassed thread, then call its start()
    method (the start() method will call the run() method).
 
    This program demonstrates both a running time-of-day clock, and an elapsed time clock.
    It also demonstrates the difference between an external class (DateClock.java) and a
    named inner class (TimerClock).
    
 */
 
 import java.awt.*;
 import java.awt.event.*;
 import javax.swing.*;
 import java.util.*;
 
 public class Threader extends JFrame implements ActionListener
 {
   private JLabel clockLabel;
   private JTextField counter1,counter2,upperLimit;
   private JButton startButton1,startButton2;
 
   private DateClock dateClock;                          // threaded time-of-day clock
   private Counter counter;                              // threaded counter
   
   public static void main(String[] args)                // main method
   {
     new Threader();                                     // instantiate a Threader object
   }
   
   public Threader()
   {
     this.setTitle("Threader");                          // setTitle() is inherited from superclass
     this.setSize(800,600);                              //  as is setSize(); operate on current GUI1 object
 
     this.setLayout(new BorderLayout(0,75));             // set the GUI's layout manager
 
     JPanel bottomPanel=new JPanel();                    // instantiate two Panel objects (containers)
     JPanel centerPanel=new JPanel();
 
     clockLabel=new JLabel();
     this.add(clockLabel,BorderLayout.NORTH);            // add the Label object to NORTH section of screen
 
     bottomPanel.add(new JLabel("Enter upper limit:"));  // start populating a Panel for bottom of screen
     
     upperLimit=new JTextField(10);
     bottomPanel.add(upperLimit);
 
     startButton1=new JButton("Unthreaded Start");
     startButton1.addActionListener(this);               // register event listener for event source
     bottomPanel.add(startButton1);
 
     startButton2=new JButton("Threaded Start");
     startButton2.addActionListener(this);               // register event listener for event source
     bottomPanel.add(startButton2);
 
     this.add(bottomPanel,BorderLayout.SOUTH);           // add Panel to SOUTH section of screen
 
     centerPanel.add(new JLabel("unthreaded:"));         // start populating the center Panel
 
     counter1=new JTextField(10);
     counter1.setEditable(false);
     centerPanel.add(counter1);
 
     centerPanel.add(new JLabel("threaded:"));
 
     counter2=new JTextField(10);
     counter2.setEditable(false);
     centerPanel.add(counter2);
 
     this.add(centerPanel,BorderLayout.CENTER);          // add third panel to CENTER of screen
     
     dateClock=new DateClock(clockLabel);                // instantiate DateClock object
                                                         //  (pass label for time display)
     dateClock.start();                                  // start dateClock execution
 
     this.setVisible(true);                              // make the GUI visible
   }
 
   public void actionPerformed(ActionEvent e)            // respond to button click
   {
     int maxValue;
     try                                                 // try to get numeric representation of
     {                                                   //  contents of input field
       maxValue=Integer.parseInt(upperLimit.getText());
     }
     catch(Exception ex)                                 // catch conversion error
     {
       maxValue=0;
     }
 
     if(e.getSource()==startButton1)
     {
       counter1.setText("");
       for(int i=1;i<=maxValue;i++)
       {
         counter1.setText(Integer.toString(i));          // change contents in textfield
       }
     }
     
     if(e.getSource()==startButton2)
     {
       counter2.setText("");
       Counter counter=new Counter(maxValue);            // instantiate new Counter object
       counter.start();                                  // call its start method
 
       counter=null;                                     // remove reference to CounterClock object
     }
   }
   
   class Counter extends Thread
   {
     private int maxValue;
     
     public Counter(int m)
     {
       this.maxValue=m;
     }
     
     public void run()                                   // executes any time thread is running
     {
       for(int i=0;i<=this.maxValue;i++)                 // counting loop
       {
         counter2.setText(""+i);                         // set label text to count
 
         try
         {
           Thread.sleep(5);                              // put thread to sleep for 5 milliseconds
         }
         catch(InterruptedException e)                   // sleep may throw an exception
         {
           break;                                        // if so, break from loop
         }
       }
     }
   }
 }

DateClock.java

/* File: DateClock.java
 
    DateClock subclasses java.util.Thread to implement a running time-of-day clock by creating
    a separate execution thread for the clock.
 
    In subclassing a Thread, you will usually over-ride the run method to provide the
    desired functionality of your thread.
 
 */
 
 import javax.swing.*;
 import java.util.*;
 
 public class DateClock extends Thread                   // subclass the Thread class
 {
   private JLabel clockLabel;                             // instance variable
 
   public DateClock(JLabel l)                              // constructor method
   {
     this.clockLabel=l;                                  // set instance variable to refer to passed object
   }
 
   public void run()                                     // executes any time thread is running
   {
     while (true)                                        // loop forever
     {
       GregorianCalendar calendar=new GregorianCalendar();    // instantiate a GregorianCalendar object
       this.clockLabel.setText(calendar.getTime().toString());
       try
       {
         Thread.sleep(1000);                            // put thread to sleep for 1 second
       }
       catch(InterruptedException e)                     // sleep may throw an exception
       {
         break;                                          // if so, break from while loop
       }
     }
   }
 }

ServletHello.java

/* File: ServletHello.java
 
    This is a simple Java servlet that displays Hello World on the user's web browser.
    The .class file for this servlet must be stored in your tomcat "classes" subdirectory.
    
    tomcat/webapps/ROOT/WEB-INF/classes
    
    Your tomcat server must be running, and you must specify the correct primary port
    number when you try to access this class file from your browser.
    
    The servlet must be entered into your web.xml file (which is in your WEB-INF directory):
    
    <servlet>
      <servlet-name>ServletHello</servlet-name>
      <servlet-class>ServletHello</servlet-class>
    </servlet>
    <servlet-mapping>
      <servlet-name>ServletHello</servlet-name>
      <url-pattern>*.ServletHello</url-pattern>
    </servlet-mapping>
 
   IMPORTANT: Any time you change your web.xml, you must stoptom and starttom to re-process
   the web.xml file.
 
   Access the servlet with:
   
   http://mislab.business.msstate.edu:8080/servlet/abc123.ServletHello
   
   (substitute your primary port number for "8080" and your net id for "abc123")
 
 */
 
 import java.io.*;                                       // import statements
 import javax.servlet.*;
 import javax.servlet.http.*;
 
 public class ServletHello extends HttpServlet           // subclass the HttpServlet class
 {
                                                         // over-ride the doGet method so we can respond
                                                         //  to a Get method request
                                                         // code in this method may throw an Exception,
                                                         //  so this method throws it as well
   public void doGet(HttpServletRequest request,HttpServletResponse response)
                     throws ServletException,IOException
   {
     response.setContentType("text/html");               // set the response header (content-type)
 
     PrintWriter out=response.getWriter();               // get a PrintWriter object to print to browser
     out.println("Hello World");                         // use it to generate some output
   }
 
 }

ReadFile.java

/* File:   ReadFile.java
    
   This servlet reads the contents of the file ServletHello.java and displays it to the browser
   as plain text (not to be rendered by the browser).
 
   Both the .class file for this servlet and the file that it reads (ServletHello.java) must be
   stored in your tomcat "classes" subdirectory"
 
   The servlet must be entered into your web.xml file (which is in your WEB-INF directory).
   
 */
 
 import java.io.*;                                       // import statements
 import javax.servlet.*;
 import javax.servlet.http.*;
 
 public class ReadFile extends HttpServlet
 {
   public void doGet(HttpServletRequest request,HttpServletResponse response)
                     throws ServletException,IOException
   {
     response.setContentType("text/plain");              // set the response header (content-type)
 
     String filename="/home/rpearson/tomcat/webapps/ROOT/WEB-INF/classes/ServletHello.java";
     PrintWriter out=response.getWriter();               // get a PrintWriter object to print to browser
     
     try                                                 // put I/O stuff in a try/catch block
     {
       BufferedReader in=new BufferedReader(new FileReader(filename));  // data file is now open
 
       String record=in.readLine();                      // attempt to read next record
       while(record!=null)                               // execute loop if record was read
       {
         out.println(record);                            // print this record, then
         record=in.readLine();                           // attempt to read next record
       }
       in.close();                                       // close the file
     }
     catch(Exception e)                                  // catch any exceptions
     {
       out.println("error attempting to open "+filename);
       out.println(e.toString());
     }
 
   }
 }

AllTrivia.java

/* File:   AllTrivia.java
    
   This servlet reads the contents of the file Trivia.fil and displays its trivia events
   to the browser as an HTML table (to be rendered by the browser).
 
   Both the .class file for this servlet and the file that it reads (Trivia.fil) must be
   stored in your tomcat "classes" subdirectory.
 
   The servlet must be entered into your web.xml file (which is in your WEB-INF directory).
   
   Since Trivia.fil contains fixed-length records, this program uses the String class's
   substring method to extract fields from the records.
   
 */
 
 import java.io.*;                                       // import statements
 import javax.servlet.*;
 import javax.servlet.http.*;
 
 public class AllTrivia extends HttpServlet              // servlets subclass the HttpServlet class
 {
   public void doGet(HttpServletRequest request,HttpServletResponse response)
                     throws ServletException,IOException
   {
     response.setContentType("text/html");               // set the response header (content-type)
 
     PrintWriter out=response.getWriter();               // get a PrintWriter object to print to browser
     
     out.println("<!doctype html>");                     // generate valid HTML for a web page
     out.println("<html>");
     out.println("<head>");
     out.println("<title>AllTrivia</title>");
     out.println("<link rel=stylesheet type='text/css' href='/BIS3523.css'>");
     out.println("</head>");
     out.println("<body>");
     
     out.println("<table>");   
     try                                                 // put I/O stuff in a try/catch block
     {
       String filename="/home/rpearson/tomcat/webapps/ROOT/WEB-INF/classes/Trivia.fil";
       BufferedReader in=new BufferedReader(new FileReader(filename));  // data file is now open
 
       String record=in.readLine();                      // attempt to read next record
       while(record!=null)                               // execute loop if record was read
       {
         String date=record.substring(0,10);
         String event=record.substring(12);
         out.println("<tr><td>"+date+"</td><td>"+event+"</td></tr>");
 
         record=in.readLine();                           // attempt to read next record
       }
       in.close();                                       // close the file
       
     }
     catch(Exception e)                                  // catch any exceptions
     {
       out.print("<tr><td>error attempting to process Trivia.fil<br>");
       out.print(e.toString());
       out.println("</td></tr>");
     }
 
     out.println("</table>");
     out.println("</body>");
     out.println("</html>");
   }
 }

BIS3523.css

BIS3523.css
 table,td
 {
   border: thin solid black;
 }
 
 table
 {
   border-collapse: collapse;
 }
 
 td
 {
   padding: 6px;
 }
 
 .noBorder {border: none}
 
 .left {text-align: left}
 .center {text-align: center}
 .right {text-align: right}
 
 .highlight:hover
 {
   color: black;
   background-color: yellow;
 }

ServerTrivia.java

/* File:   ServerTrivia.java
    
   This servlet reads the contents of the file Trivia.dat and displays today's trivia events
   to the browser as an HTML table (to be rendered by the browser). "Today" is based on the
   server's date and time, not the client.
 
   Since Trivia.dat contains variable-length, delimited records, this program uses the String
   class's split method to split the records into their subordinate fields.
   
   This program uses methods of the "deprecated" Date class. You will get a warning when you
   compile, but the methods still work. They're deprecated, they're not obsolete.
   
 */
 
 import java.io.*;                                       // import statements
 import javax.servlet.*;
 import javax.servlet.http.*;
 import java.util.*;
 
 public class ServerTrivia extends HttpServlet
 {
   public void doGet(HttpServletRequest request,HttpServletResponse response)
                     throws ServletException,IOException
   {
     response.setContentType("text/html");              // set the response header (content-type)
 
     Date date=new Date();                               // instantiate a Date object (deprecated)
     int todayMonth=date.getMonth()+1;                   // getMonth returns 0-11 (increment by 1)
     int todayDay=date.getDate();                        // day of the month (1-31)
     int listCount=0;                                    // initialize a counter
                                                         // generate a heading
     PrintWriter out=response.getWriter();               // get a PrintWriter object to print to browser
 
     out.println("<!doctype html>");                     // generate valid HTML for a web page
     out.println("<html>");
     out.println("<head>");
     out.println("<title>ServerTrivia</title>");
     out.println("<link rel=stylesheet type='text/css' href='/BIS3523.css'>");
     out.println("</head>");
     out.println("<body>");
     
     out.println("<table>");   
     out.println("<tr><td colspan=2>On "+todayMonth+"/"+todayDay+", the following events happened:</td></tr>");
 
     try                                                 // put I/O stuff in a try/catch block
     {
       String filename="/home/rpearson/tomcat/webapps/ROOT/WEB-INF/classes/Trivia.dat";
       BufferedReader in=new BufferedReader(new FileReader(filename));  // data file is now open
 
       String record=in.readLine();                      // attempt to read next record
       while(record!=null)                               // execute loop if record was read
       {
         String[] fields=record.split("\t");
         int thisMonth=Integer.parseInt(fields[0]);
         int thisDay=Integer.parseInt(fields[1]);
         
         if(todayMonth==thisMonth && todayDay==thisDay)
         {
           out.println("<tr><td>"+fields[2]+"</td><td>"+fields[3]+"</td></tr>");
           listCount++;
         }
         
         record=in.readLine();                           // attempt to read next record
       }
       in.close();                                       // close the file
       
     }
     catch(Exception e)                                  // catch any exceptions
     {
       out.print("<tr><td>error attempting to process Trivia.dat<br>");
       out.print(e.toString());
       out.println("</td></tr>");
     }
 
     out.println("<tr><td colspan=2>"+listCount+" trivia events listed</td></tr>");
     out.println("</table>");
     
     out.println("</body>");
     out.println("</html>");
   }
 }

Trivia.dat

Sample records from Trivia.dat (variable-length, tab-delimited records)
each record consists of: month, tab, day, tab, year, tab, trivia event
	Giuseppe Piazzi discoved 1st asteroid, later named Ceres
	United Kingdom of Great Britain & Ireland established
	Haiti gains its independence
	Emancipation Proclamation issued by Lincoln.
	Brooklyn merges with NY to form present City of NY Ellis Island became reception center for new...
	Commonwealth of Australia established
	first Rose Bowl game held in Pasadena, California.
	first running of SF's famed "Bay to Breakers" race (7.63 miles)
	Alcatraz officially becomes a Federal Prison.
	Sudan gains its independence
	European Economic Community (EEC) starts operation.
	Cigarette advertisements banned on TV
	AT & T broken up into 8 companies.
	Spain & Portugal become 11th & 12th members of Common Market
	first American revolutionary flag displayed.
	Georgia is 4th state to ratify US constitution
	World's Columbian Exposition opens in Chicago
	DeYoung Museum in San Francisco's Golden Gate Park opens.
	first electron tube described, St Louis, Missouri
	USSR launches Mechta, 1st lunar probe & artificial in solar orbit
	Dr Christian Barnard performs 1st successful heart transplant
	Mariner 9 begins mapping Mars
	Martin Luther excommunicated by Roman Catholic Church
	Washington defeats British at Battle of Princeton, NJ
	First Chinese arrive in Hawaii.
	Brooklyn Bridge begun, completed on May 24, 1883
st drinking straw is patented.
	first electric watch introduced, Lancaster Pennsylvania
	Alaska becomes the 49th state.
	Apple Computer incorporated.

AjaxTrivia.html

<!doctype html>
 
 <html>
 <head>
 <title>AjaxTrivia.html</title>
 <meta charset='utf-8'>
 
 <!-- File: AjaxTrivia.html
 
   This web page uses AJAX concepts to load a standard HTML document, then use Javascript
   to get the client's month and day, submitting them to a servlet, which will respond
   with the appropriate trivia events. A Javascript "callback" function receives the response,
   and displays the response in a table on the current page.
   
 -->
 
 <link rel=stylesheet type='text/css' href='/BIS3523.css'>
 
 <script type='text/javascript'>
 
 function start()
 {
   // get the client's month and day
   var date=new Date();
   var month=date.getMonth()+1;
   var day=date.getDate();
 
   // construct an AJAX request for the AjaxTrivia servlet
   // appending two name=value pairs of data to submit to the servlet  
   url='/servlet/rap10.AjaxTrivia?month='+month+'&day='+day;
   var element=document.getElementById('triviaTable');
   element.innerHTML='<tr><td>submitting request '+url+'</td></tr>';
   request=new XMLHttpRequest();
   request.open('get',url);
   request.send(null);
 
   // set up the "callback" function
   request.onreadystatechange=responseHandler;
 }
 
 function responseHandler()
 {
   // when our request's readyState property is 4, we have the server's response
   // use it as our table's new innerHTML
   if(request.readyState==4)
   {
     var element=document.getElementById('triviaTable');
     element.innerHTML=request.response;
   }
 }
 
 </script>
 
 </head>
 <body onLoad='start()'>
 
 <table id=triviaTable>
 </table>
 
 </body>
 </html>

AjaxTrivia.java

 /* File:   AjaxTrivia.java
    
   This servlet reads the contents of the file Trivia.dat and echoes today's trivia events
   to the browser as an HTML table (to be rendered by the browser). "Today" is based on the
   server's date and time, not the client.
 
   Since Trivia.dat contains variable-length, delimited records, this program uses the String
   class's split method to split the records into their subordinate fields.
   
 */
 
 import java.io.*;                                       // import statements
 import javax.servlet.*;
 import javax.servlet.http.*;
 import java.util.*;
 
 public class AjaxTrivia extends HttpServlet
 {
   public void doGet(HttpServletRequest request,HttpServletResponse response)
                     throws ServletException,IOException
   {
     response.setContentType("text/html");               // set the response header (content-type)
 
     // retrieve two pieces of submitted data (submitted in name=value format)
     int todayMonth=Integer.parseInt(request.getParameter("month"));
     int todayDay=Integer.parseInt(request.getParameter("day"));
     
     int listCount=0;                                    // initialize a counter
                                                         // generate a heading
     PrintWriter out=response.getWriter();               // get a PrintWriter object to print to browser
  
     out.println("<tr><td colspan=2>On "+todayMonth+"/"+todayDay+", the following events happened:</td></tr>");
 
     try                                                 // put I/O stuff in a try/catch block
     {
       String filename="/home/rpearson/tomcat/webapps/ROOT/WEB-INF/classes/Trivia.dat";
       BufferedReader in=new BufferedReader(new FileReader(filename));  // data file is now open
 
       String record=in.readLine();                      // attempt to read next record
       while(record!=null)                               // execute loop if record was read
       {
         String[] fields=record.split("\t");
         int thisMonth=Integer.parseInt(fields[0]);
         int thisDay=Integer.parseInt(fields[1]);
         
         if(todayMonth==thisMonth && todayDay==thisDay)
         {
           out.println("<tr><td>"+fields[2]+"</td><td>"+fields[3]+"</td></tr>");
           listCount++;
         }
         
         record=in.readLine();                           // attempt to read next record
       }
       in.close();                                       // close the file
       
     }
     catch(Exception e)                                  // catch any exceptions
     {
       out.println("<tr><td>error attempting to open Trivia.dat</td></tr>");
       out.println(e.toString());
     }
 
     out.println("<tr><td colspan=2>"+listCount+" trivia events listed</td></tr>");
     
   }
 }

AjaxLogin.html

<!doctype html>
 
 <html>
 <head>
 <title>AjaxLogin.html</title>
 <meta charset='utf-8'>
 
 <!-- File: AjaxLogin.html
 
   This page uses AJAX concepts to provide login/password data validation.
   
 -->
 
 <link rel=stylesheet type='text/css' href='/BIS3523.css'>
 <style type='text/css'>
 table,td
 {
   border: none;
 }
 </style>
 
 <script type='text/javascript'>
 
 function submitRequest()
 {
   // retreive the login and the password from the form fields
   var loginData=document.getElementById('loginField').value;
   var passwordData=document.getElementById('passwordField').value;
 
   // construct an HTTP request, complete with two name=value pairs of form data 
   url='/servlet/rap10.AjaxLogin?login='+loginData+'&password='+passwordData;
 
   // prepare and submit the AJAX request
   request=new XMLHttpRequest();
   request.open('get',url);
   request.send(null);
   
   // set up a callback function to be called any time the readyState property changes
   request.onreadystatechange=responseHandler;
 }
 
 // the callback function
 function responseHandler()
 {
 
   // we're really interested only in a readyState value of 4
   if(request.readyState==4)
   {
   
     // get references to the two td's we use to display messages
     var loginElement=document.getElementById('loginMsg');
     var passwordElement=document.getElementById('passwordMsg');
     loginElement.innerHTML='';
     passwordElement.innerHTML='';
 
     // process the AJAX response by updating the msg td's
     if(request.response=='login')
     {
       loginElement.innerHTML='invalid login';
       loginElement.style.color='red';
     }
     if(request.response=='password')
     {
       passwordElement.innerHTML='invalid password';
       passwordElement.style.color='red';
     }
     if(request.response=='valid')
     {
       document.location='http://mislab.business.msstate.edu';
     }
   }
 }
 
 </script>
 
 </head>
 <body>
 
 <form>
 
 <table id=triviaTable>
   <tr>
     <td>Login id:</td>
     <td><input type=text id=loginField></td>
     <td id=loginMsg></td>
   </tr>
   <tr>
     <td>Password:</td>
     <td><input type=password id=passwordField></td>
     <td id=passwordMsg></td>
   </tr>
   <tr>
     <td></td>
     <td><input type=button onClick='submitRequest()' value='  Login  '></td>
     <td></td>
   </tr>
 </table>
 
 </form>
 
 </body>
 </html>

AjaxLogin.java

/* File:   AjaxLogin.java
 
 This servlet accepts a submitted login id and password, then checks for the existence
 of the login id in the server-based file ValidLogins.dat, and verifies that the
 submitted password matches the associated password in the file.   
 
 Since ValidLogins.txt contains variable-length, delimited fields (delimited by tab characters),
 the String class's split method is used to split the record into its sub-fields. The split method
 returns an array of String objects.
 
 This servlet responds to an AJAX request, and responds with the word:
 login - if the login id was not found in ValidLogins.dat
 password - if the login id was found but the submitted password did not match
 valid - if login id and password were valid
 
 On a successful login, the servlet adds a record to a login-tracking file.
 
 */
 
 import java.io.*;                                       // import statements
 import javax.servlet.*;
 import javax.servlet.http.*;
 import java.util.*;
 
 public class AjaxLogin extends HttpServlet
 {
   public void doGet(HttpServletRequest request,HttpServletResponse response)
                     throws ServletException,IOException
   {
     response.setContentType("text/plain");             // set the response header (content-type)
 
     // retrieve the two pieces of submitted data
     // also, set a flag to false
     String login=request.getParameter("login");
     String password=request.getParameter("password");
     boolean found=false;
         
     PrintWriter out=response.getWriter();               // get a PrintWriter object to print to browser
     BufferedReader in=null;
     
     try                                                 // put I/O stuff in a try/catch block
     {                                                   // try to open the ValidLogins.dat data file
       in=new BufferedReader(new FileReader(
"/home/rpearson/tomcat/webapps/ROOT/WEB-INF/classes/ValidLogins.dat"));
 
       String record=in.readLine();                      // attempt to read next record
       while(record!=null)                               // execute loop if record was read
       {
         String[] fields=record.split("\t");             // split record into its sub-fields
         
         if(login.equals(fields[0]))                     // does submitted login match field #0?
         {
           found=true;                                   // if so, set flag to true
           if(password.equals(fields[1]))                // and check to see if submitted password matches
           {                                             // field #1
             in.close();
             out.print("valid");                         // echo response back to client
             this.logfile(login);                        // call our logfile method
             return;                                     // exit the doGet function
           }
           else
           {
             in.close();
             out.print("password");                      // echo response back to client
             return;                                     // and exit the doGet function
           }
         }
         
         record=in.readLine();                           // attempt to read next record
       }
       
     }
     catch(Exception e)                                  // catch any exceptions
     {
     }
     in.close();                                         // close the file
 
     if(!found)                                          // if flag was never changed to true
     {
       out.print("login");                               // echo appropriate message back to client
     }                                                   // (submitted login was not found in file)
     
   }
   
   private void logfile(String login)                    // our logfile method
   {                                                     // writes a record into a log file
     try
     {
       Date date=new Date();
 
       FileWriter file=new FileWriter("LoginLog.txt");
       file.write(login+"\t"+date.toString()+"\n");
       file.close();
     }
     catch(Exception e)
     {
     }
   }
 }

ValidLogins.dat

ValidLogins.dat (variable-length, tab-delimited records)
each record consists of: login id, tab, corresponding password

rap10	password
gb497	1119
cac834	1111
tc318	1105
ng254	1105
wh373	1108
zbm6	2698
jds835	1116

A Brief Overview of Java Server Page (JSP) programming

JSP has four predefined variables:

  • request
    • the HttpServletRequest object
  • response
    • the HttpServletResponse object
  • out
    • PrintWriter object used to send output to client
  • session
    • HttpSession object associated with request

      JSP includes four scripting elements:

      JSP page directive
      <%@ page import="java.util.*" %>

      The main use of a JSP page directive is to include imports for the compiler.

      JSP declaration
      <%! private int accessCount=0; %>

      A JSP declaration is used to define, and possibly initialize, a variable. The declaration
      is executed only the first time the .jsp page is executed (after translation).

      JSP expression
      <%= new Date() %>

      A JSP "expression" is used to insert a value directly into the output. The expression
      is evaluated, converted to a String, and inserted into the page.

      JSP scriptlet
      <%
      String wordList=(String) session.getAttribute("wordList");
      if(wordList==null)
      {
      out.println("wordList is empty");
      }
      else
      {
      out.println(wordList);
      }
      %>

      A JSP "scriptlet" is a block of Java code that will be executed.

Counter.jsp

 

Trivia.jsp

 

Customer.jsp

 

AjaxCustomer.jsp

 

AjaxCustomer.java

 

CustomerDatabaseList.java

 

CustomerDatabaseListServlet.java

 

CustomerDatabaseQuery.html

 

CustomerDatabaseQuery.java

 

CustomerDatabaseUpdate.jsp

 

CustomerDatabaseUpdate.java

 

SessionTracker.jsp

 

SessionTracker.java

 

SessionLister.java