Ex Package
Ex Package
Ex Package
(A CHRISTIAN MINORITY INSTITUTION) JAISAKTHI EDUCATIONAL TRUST BANGALORE TRUNK ROAD, VARATHARAJAPURAM, NASARATHPET, POONAMALLEE, CHENNAI -602 123
Subject: IT2305 - JAVA PROGRAMMING LAB Class: III year IT List of Experiments:
1. Develop a Java package with simple Stack and Queue classes. Use JavaDoc comments for documentation. 2. Design a class for Complex numbers in Java. In addition to methods for basic operations on complex numbers, provide a method to return the number of active objects created. 3. Design a Date class similar to the one provided in the java.util package. 4. Develop with suitable hierarchy, classes for Point, Shape, Rectangle, Square, Circle, Ellipse, Triangle, Polygon, etc. Design a simple test application to demonstrate dynamic polymorphism. 5. Design a Java interface for ADT Stack. Develop two different classes that implement this interface, one using array and the other using linked-list. Provide necessary exception handling in both the implementations. 6. Write a Java program to read a file that contains DNA sequences of arbitrary length one per line (note that each DNA sequence is just a String). Your program should sort the sequences in descending order with respect to the number of 'TATA' subsequences present. Finally write the sequences in sorted order into another file. 7. Develop a simple paint-like program that can draw basic graphical primitives in different dimensions and colors. Use appropriate menu and buttons. 8. Develop a scientific calculator using even-driven programming paradigm of Java. 9. Develop a template for linked-list class along with its methods in Java. 10. Design a thread-safe implementation of Queue class. Write a multi-threaded producer-consumer application that uses this Queue class. 11. Write a multi-threaded Java program to print all numbers below 100,000 that are both prime and fibonacci number (some examples are 2, 3, 5, 13, etc.). Design a thread that generates prime numbers below 100,000 and writes them into a pipe. Design another thread that generates fibonacci numbers and writes them to another pipe. The main thread should read both the pipes to identify numbers common to both. 12. Develop a multi-threaded GUI application of your choice.
Ex no 1: To Develop a Java package with simple Stack and Queue classes. Use JavaDoc comments for documentation.
JAVA DOCUMENTATION:
Javadoc is a documentation generator from Sun Microsystems for generating API documentation in HTML format from Java source code. The "doc comments" format used by Javadoc is the de facto industry standard for documenting Java classes. Some IDEs, such as Netbeans and Eclipse automatically generate Javadoc HTML. Many file editors assist the user in producing Javadoc source and use the Javadoc info as internal references for the programmer. Javadoc also provides an API for creating doclets and taglets, which allows you to analyze the structure of a Java application. This is how JDiff can generate reports of what changed between two versions of an API. Structure of a Javadoc comment A Javadoc comment is set off from code by standard multi-line comment tags /* and */. The opening tag, however, has an extra asterisk, as in /**. 1. The first paragraph is a description of the method documented. 2. Following the description are a varying number of descriptive tags, signifying: 1. The parameters of the method (@param) 2. What the method returns (@return) 3. Any exceptions the method may throw (@throws) 4. Other less-common tags such as @see (a "see also" tag) Overview of Javadoc The basic structure of writing document comments is embed them inside /** ... */. The Javadoc is written next to the items without any separating newline. The class declaration usually contains: /** * @author Firstname Lastname <address @ example.com> * @version 1.6 (The Java version used) * @since 2010.0331 (E.g. ISO 8601 YYYY.MMDD) */ public class Test { // class body } For methods there is (1) a short, concise, one line description to explain what the item does. This is followed by [2] a longer description that may span in multiple paragraphs. In those the details can be explained in full. This section, marked in brackets [], is optional. Last, there is (3) a tag section to list the accepted input arguments and return values of the method. /** * Short one line description. *
(1)
* Longer description. If there were any, it would be [2] * here. * * @param variable Description text text text. (3) * @return Description text text text. */ Variables are documented similarly to methods with the exception that part (3) is omitted. Here the variable contains only the short description: /** * Description of the variable here. */ private int debug = 0; Some of the available Javadoc tags[2] are listed in the table below: Tag & Parameter @author name @version version @since since-text @see reference Usage Applies to Sinc e
Describes an author. Class, Interface Provides version entry. Max one per Class, Interface Class or Interface. Describes since when this Class, Interface, functionality has existed. Field, Method Provides a link to other element of Class, Interface, documentation. Field, Method
@param name Describes a method parameter. Method description @return description Describes the return value. Method @exception classname description Describes an exception that may be Method @throws classname thrown from this method. description @deprecated Describes an outdated method. Method description Copies the description from the {@inheritDoc} Overriding Method 1.4.0 overridden method. Class, Interface, {@link reference} Link to other symbol. Field, Method {@value} Return the value of a static field. Static Field 1.4.0 Example An example of using Javadoc to document a method follows. Notice that spacing and number of characters in this example are as conventions state. /** * Validates a chess move. * * Use {@link #doMove(int, int, int, int)} to move a piece. * * @param theFromFile file from which a piece is being moved * @param theFromRank rank from which a piece is being moved * @param theToFile file to which a piece is being moved * @param theToRank rank to which a piece is being moved
* @return true if the move is valid, otherwise false */ boolean isValidMove(int theFromFile, int theFromRank, int theToFile, int theToRank) { ... } /** * Moves a chess piece. * * @see java.math.RoundingMode */ boolean doMove(int theFromFile, int theFromRank, int theToFile, int theToRank) { ... }
Packages:
Definition: A package is a grouping of related types providing access protection and name space management. Note that types refers to classes, interfaces, enumerations, and annotation types. Enumerations and annotation types are special kinds of classes and interfaces, respectively, so types are often referred to in this lesson simply as classes and interfaces. Creating a Package : Step 1: To Create a package , you have to create a Directory in our program I created the simplepackage .
Step2: Inside of this directory you create classes. For example ClassA and ClassB classes are created inside the simplepackage directory. Step3: One important note, very class file should contain first line name of the package, for example ClassA.java package simplepackage;
Compiling and Running a package: Step4: F:\Mohan_CSE_staff>javac simplepackage\ClassB.java for the ClassB and ClassA you do F:\Mohan_CSE_staff>javac simplepackage\ClassA.java Step5: You will run only ClassA file , that is ClassA file contains no need to run ClassB F:\Mohan_CSE_staff>javac simplepackage.ClassA
Stack Program:
StackDisplay.java : package simplepackage; class StackDisplay { public static void main(String[] args) { StackDemo.displayStack(); } }
StackDemo.java : // Demonstrate the Stack class. package simplepackage; import java.util.*; class StackDemo { static void showpush(Stack st, int a) { st.push(new Integer(a)); System.out.println("push(" + a + ")");
System.out.println("stack: " + st); } static void showpop(Stack st) { System.out.print("pop -> "); Integer a = (Integer) st.pop(); System.out.println(a); System.out.println("stack: " + st); } static void displayStack() { Stack st = new Stack(); System.out.println("stack: " + st); showpush(st, 42); showpush(st, 66); showpush(st, 99); showpop(st); showpop(st); showpop(st); try { showpop(st); } catch (EmptyStackException e) { System.out.println("empty stack"); } } } Compiling : F:\Mohan_CSE_staff>javac simplepackage\ StackDemo.java F:\Mohan_CSE_staff>javac simplepackage\ StackDisplay.java Running : F:\Mohan_CSE_staff>java simplepackage.StackDisplay
Queue Program:
QueueDisplay.java : package simplepackage; class QueueDisplay { public static void main(String[] args) { QueueExample.displayQueue(); } }
QueueExample.java :
package simplepackage; import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; public class QueueExample { static void displayQueue() { Queue<String> qe=new LinkedList<String>(); qe.add("b"); qe.add("a"); qe.add("c"); qe.add("e"); qe.add("d"); Iterator it=qe.iterator(); System.out.println("Initial Size of Queue :"+qe.size()); while(it.hasNext()) { String iteratorValue=(String)it.next(); System.out.println("Queue Next Value :"+iteratorValue); } // get value and does not remove element from queue System.out.println("Queue peek :"+qe.peek()); // get first value and remove that object from queue System.out.println("Queue poll :"+qe.poll()); System.out.println("Final Size of Queue :"+qe.size()); } }
Compiling : F:\Mohan_CSE_staff>javac simplepackage\ QueueExample.java F:\Mohan_CSE_staff>javac simplepackage\ QueueDisplay.java Running : F:\Mohan_CSE_staff>java simplepackage. QueueDisplay
Ex no 2: Design a class for Complex numbers in Java. In addition to methods for basic operations on complex numbers, provide a method to return the number of active objects created.
ComplexDemo.java : /* 3.0+5.0i 3.0+5.0i.getReal() = 3.0 3.0+5.0i + 2.0-2.0i = 5.0+3.0i 3.0+5.0i + 2.0-2.0i = 5.0+3.0i 3.0+5.0i * 2.0-2.0i = 16.0+4.0i -0.5+2.0i */
/** A class to test Complex Numbers. * @author Mohanapraksh, http://www.pitinfo.com/ * @version $Id: ComplexDemo.java,v 1.6 2011/05/13 15:28:59 Exp $ */ public class ComplexDemo { /** The program */ public static void main(String[] args) { Complex c = new Complex(3, 5); Complex d = new Complex(2, -2); System.out.println(c); System.out.println(c + ".getReal() = " + c.getReal()); System.out.println(c + " + " + d + " = " + c.add(d)); System.out.println(c + " + " + d + " = " + Complex.add(c, d)); System.out.println(c + " * " + d + " = " + c.multiply(d)); System.out.println(Complex.divide(c, d)); } } /** A class to represent Complex Numbers. A Complex object is * immutable once created; the add, subtract and multiply routines * return newly-created Complex objects containing the results. * * @author Mohanapraksh, inspired by Java. * @version $Id: Complex.java,v 1.3 2011/05/13 15:28:59 Exp $ */ class Complex { /** The real part */ private double r; /** The imaginary part */ private double i; /** Construct a Complex */ Complex(double rr, double ii) { r = rr; i = ii; } /** Display the current Complex as a String, for use in * println() and elsewhere. */ public String toString() { StringBuffer sb = new StringBuffer().append(r);
/** Return just the Real part */ public double getReal() { return r; } /** Return just the Real part */ public double getImaginary() { return i; } /** Return the magnitude of a complex number */ public double magnitude() { return Math.sqrt(r*r + i*i); } /** Add another Complex to this one */ public Complex add(Complex other) { return add(this, other); } /** Add two Complexes */ public static Complex add(Complex c1, Complex c2) { return new Complex(c1.r+c2.r, c1.i+c2.i); } /** Subtract another Complex from this one */ public Complex subtract(Complex other) { return subtract(this, other); } /** Subtract two Complexes */ public static Complex subtract(Complex c1, Complex c2) { return new Complex(c1.r-c2.r, c1.i-c2.i); } /** Multiply this Complex times another one */ public Complex multiply(Complex other) { return multiply(this, other); } /** Multiply two Complexes */ public static Complex multiply(Complex c1, Complex c2) { return new Complex(c1.r*c2.r - c1.i*c2.i, c1.r*c2.i + c1.i*c2.r); } /** Divide c1 by c2. * @author Gisbert Selke. */ public static Complex divide(Complex c1, Complex c2) {
/* Compare this Complex number with another */ public boolean equals(Object o) { if (!(o instanceof Complex)) throw new IllegalArgumentException( "Complex.equals argument must be a Complex"); Complex other = (Complex)o; return r == other.r && i == other.i; } /* Generate a hashCode; not sure how well distributed these are. */ public int hashCode() { return (int)( r) | (int)i; } } Ex No 3. Design a Date class similar to the one provided in the java.util package.
/** * @author Mohanapraksh, http://www.pitinfo.com/ * @version $Id: ComplexDemo.java,v 1.6 2011/05/13 15:28:59 Exp $ */ import import import import java.util.Date; java.util.Calendar; java.util.TimeZone; java.io.Serializable;
/** * A time-less Date class for basic date arithmetics. */ public class Day implements Comparable, Cloneable, Serializable { protected Calendar calendar_; /** * Initialize the internal calendar instance. * * @param year Year of new day. * @param month Month of new day. * @param dayOfMonth Day of month of new day. */ private void initialize (int year, int month, int dayOfMonth) { calendar_ = Calendar.getInstance();
calendar_.setLenient (true); calendar_.setFirstDayOfWeek (Calendar.MONDAY); calendar_.setTimeZone (TimeZone.getTimeZone ("GMT")); set (year, month, dayOfMonth); } /** * Create a new day. * The day is lenient meaning that illegal day parameters can be * specified and results in a recomputed day with legal month/day * values. * * @param year Year of new day. * @param month Month of new day (0-11) * @param dayOfMonth Day of month of new day (1-31) */ public Day (int year, int month, int dayOfMonth) { initialize (year, month, dayOfMonth); }
/** * Create a new day, specifying the year and the day of year. * The day is lenient meaning that illegal day parameters can be * specified and results in a recomputed day with legal month/day * values. * * @param year Year of new day. * @param dayOfYear 1=January 1, etc. */ public Day (int year, int dayOfYear) { initialize (year, Calendar.JANUARY, 1); calendar_.set (Calendar.DAY_OF_YEAR, dayOfYear); } /** * Create a new day representing the day of creation * (according to the setting of the current machine). */ public Day() { // Now (in the currenct locale of the client machine) Calendar calendar = Calendar.getInstance(); // Prune time part initialize (calendar.get (Calendar.YEAR), calendar.get (Calendar.MONTH), calendar.get (Calendar.DAY_OF_MONTH)); } /** * Create a new day based on a java.util.Calendar instance. * NOTE: The time component from calendar will be pruned. *
* @param calendar Calendar instance to copy. */ public Day (Calendar calendar) { this (calendar.get (Calendar.YEAR), calendar.get (Calendar.MONTH), calendar.get (Calendar.DAY_OF_MONTH)); } /** * Create a new day based on a java.util.Date instance. * NOTE: The time component from date will be pruned. * * @param date Date instance to copy. */ public Day (Date date) { // Create a calendar based on given date Calendar calendar = Calendar.getInstance(); calendar.setTime (date); // Extract date values and use these only initialize (calendar.get (Calendar.YEAR), calendar.get (Calendar.MONTH), calendar.get (Calendar.DAY_OF_MONTH)); } /** * Create a new day based on a time value. * Time is milliseconds since "the Epoch" (1.1.1970). * NOTE: The time component from time will be pruned. * * @param time Milliseconds since "the Epoch". */ public Day (long time) { this (new Date (time)); } /** * Create a new day as a copy of the specified day. * * @param day Day to clone. */ public Day (Day day) { this (day.getYear(), day.getMonth(), day.getDayOfMonth()); } /** * Create a clone of this day. * * @return This day cloned. */ public Object clone() {
/** * A more explicit front-end to the Day() constructor which return a day * object representing the day of creation. * * @return A day instance representing today. */ public static Day today() { return new Day(); } /** * Return a Calendar instance representing the same day * as this instance. For use by secondary methods requiring * java.util.Calendar as input. * * @return Calendar equivalent representing this day. */ public Calendar getCalendar() { return (Calendar) calendar_.clone(); } /** * Return a Date instance representing the same date * as this instance. For use by secondary methods requiring * java.util.Date as input. * * @return Date equivalent representing this day. */ public Date getDate() { return getCalendar().getTime(); } /** * Compare this day to the specified day. If object is * not of type Day a ClassCastException is thrown. * * @param object Day object to compare to. * @return @see Comparable#compareTo(Object) * @throws ClassCastException If object is not of type Day. */ public int compareTo (Object object) { Day day = (Day) object; return calendar_.getTime().compareTo (day.calendar_.getTime()); }
/**
* Return true if this day is after the specified day. * * @param date Day to compare to. * @return True if this is after day, false otherwise. */ public boolean isAfter (Day day) { return calendar_.after (day.calendar_); }
/** * Return true if this day is before the specified day. * * @param date Day to compare to. * @return True if this is before day, false otherwise. */ public boolean isBefore (Day day) { return calendar_.before (day.calendar_); }
/** * Return true if this day equals (represent the same date) * as the specified day. * * @param date Day to compare to. * @return True if this equals day, false otherwise. */ public boolean equals (Day day) { return calendar_.equals (day.calendar_); }
/** * Overload required as default definition of equals() has changed. * * @return A hash code value for this object. */ public int hashCode() { return calendar_.hashCode(); }
/** * Set date of this day. * The day is lenient meaning that illegal day parameters can be * specified and results in a recomputed day with legal month/day * values. * * @param year Year of this day.
* @param month Month of this day (0-11). * @param dayOfMonth Day of month of this day (1-31). */ public void set (int year, int month, int dayOfMonth) { setYear (year); setMonth (month); setDayOfMonth (dayOfMonth); }
/** * Return year of this day. * * @return Year of this day. */ public int getYear() { return calendar_.get (Calendar.YEAR); } /** * Set year of this day. * * @param year New year of this day. */ public void setYear (int year) { calendar_.set (Calendar.YEAR, year); }
/** * Return month of this day. The result must be compared to Calendar.JANUARY, * Calendar.FEBRUARY, etc. * * @return Month of this day. */ public int getMonth() { return calendar_.get (Calendar.MONTH); }
/** * Return the 1-based month number of the month of this day. * 1 = January, 2 = February and so on. * * @return Month number of this month */ public int getMonthNo() { // It is tempting to return getMonth() + 1 but this is conceptually // wrong, as Calendar month is an enumeration and the values are tags // only and can be anything.
switch (getMonth()) { case Calendar.JANUARY : return 1; case Calendar.FEBRUARY : return 2; case Calendar.MARCH : return 3; case Calendar.APRIL : return 4; case Calendar.MAY : return 5; case Calendar.JUNE : return 6; case Calendar.JULY : return 7; case Calendar.AUGUST : return 8; case Calendar.SEPTEMBER : return 9; case Calendar.OCTOBER : return 10; case Calendar.NOVEMBER : return 11; case Calendar.DECEMBER : return 12; } // This will never happen return 0;
/** * Set month of this day. January = 0, February = 1, etc. * Illegal month values will result in a recomputation of * year and a resetting of month to a valid value. * I.e. setMonth(20), will add 1 year to day and set month * to 8. * * @param month New month of this day. */ public void setMonth (int month) { calendar_.set (Calendar.MONTH, month); }
/** * Return day of month of this day. * NOTE: First day of month is 1 (not 0). * * @return Day of month of this day. */ public int getDayOfMonth() { return calendar_.get (Calendar.DAY_OF_MONTH); }
/** * Set day of month of this date. 1=1st 2=2nd, etc. * Illegal day values will result in a recomputation of * month/year and a resetting of day to a valid value. * I.e. setDayOfMonth(33), will add 1 month to date and * set day to 5, 4, 3 or 2 depending on month/year. * * @param dayOfMonth New day of month of this day.
/** * Return the day number of year this day represents. * January 1 = 1 and so on. * * @return day number of year. */ public int getDayOfYear() { return calendar_.get (Calendar.DAY_OF_YEAR); }
/** * Return the day of week of this day. * NOTE: Must be compared to Calendar.MONDAY, TUSEDAY etc. * * @return Day of week of this day. */ public int getDayOfWeek() { return calendar_.get (Calendar.DAY_OF_WEEK); }
/** * Return the day number of week of this day, where * Monday=1, Tuesday=2, ... Sunday=7. * * @return Day number of week of this day. */ public int getDayNumberOfWeek() { return getDayOfWeek() == Calendar.SUNDAY ? 7 : getDayOfWeek() - Calendar.SUNDAY; }
/** * Return the week number of year, this day * belongs to. 1st=1 and so on. * * @return Week number of year of this day. */ public int getWeekOfYear() { return calendar_.get (Calendar.WEEK_OF_YEAR); }
/** * Add a number of days to this day. Subtracting a number of * days can be done by a negative argument to addDays() or calling * subtractDays() explicitly. * * @param nDays Number of days to add. */ public void addDays (int nDays) { calendar_.add (Calendar.DAY_OF_MONTH, nDays); }
/** * Subtract a number of days from this day * * @param nDays Number of days to subtract. */ public void subtractDays (int nDays) { addDays (-nDays); }
/** * Add a number of months to this day. The actual number of days added * depends on the staring day. Subtracting a number of months can be done * by a negative argument to addMonths() or calling subtactMonths() * explicitly. * NOTE: addMonth(n) m times will in general give a different result * than addMonth(m*n). Add 1 month to January 31, 2005 will give * February 28, 2005. * * @param nMonths Number of months to add. */ public void addMonths (int nMonths) { calendar_.add (Calendar.MONTH, nMonths); }
/** * Subtract a number of months from this day * @see #addMonths(int). * * @param nDays Number of days to subtract. */ public void subtractMonths (int nMonths) { addMonths (-nMonths); }
/** * Add a number of years to this day. The actual * number of days added depends on the starting day. * Subtracting a number of years can be done by a negative argument to * addYears() or calling subtractYears explicitly. * * @param nYears Number of years to add. */ public void addYears (int nYears) { calendar_.add (Calendar.YEAR, nYears); }
/** * Subtract a number of years from this day * @see #addYears(int). * * @param nYears Number of years to subtract. */ public void subtractYears (int nYears) { addYears (-nYears); }
/** * Return the number of days in the year of this day. * * @return Number of days in this year. */ public int getDaysInYear() { return calendar_.getActualMaximum (Calendar.DAY_OF_YEAR); }
/** * Return true if the year of this day is a leap year. * * @return True if this year is a leap year, false otherwise. */ public boolean isLeapYear() { return getDaysInYear() == calendar_.getMaximum (Calendar.DAY_OF_YEAR); } /** * Return true if the specified year is a leap year. * * @param year Year to check. * @return True if specified year is leap year, false otherwise.
*/ public static boolean isLeapYear (int year) { return (new Day (year, Calendar.JANUARY, 1)).isLeapYear(); }
/** * Return the number of days in the month of this day. * * @return Number of days in this month. */ public int getDaysInMonth() { return calendar_.getActualMaximum (Calendar.DAY_OF_MONTH); }
/** * Get default locale name of this day ("Monday", "Tuesday", etc. * * @return Name of day. */ public String getDayName() { switch (getDayOfWeek()) { case Calendar.MONDAY : return "Monday"; case Calendar.TUESDAY : return "Tuesday"; case Calendar.WEDNESDAY : return "Wednesday"; case Calendar.THURSDAY : return "Thursday"; case Calendar.FRIDAY : return "Friday"; case Calendar.SATURDAY : return "Saturday"; case Calendar.SUNDAY : return "Sunday"; } // This will never happen return null;
/** * Return number of days between two days. * The method always returns a positive number of days. * * @param date The day to compare to. * @return Number of days between this and day. */ public int daysBetween (Day day) { long millisBetween = Math.abs (calendar_.getTime().getTime() day.calendar_.getTime().getTime()); return (int) Math.round (millisBetween / (1000 * 60 * 60 * 24)); } /** * Find the n'th xxxxday of s specified month (for instance find 1st sunday
* of May 2006; findNthOfMonth (1, Calendar.SUNDAY, Calendar.MAY, 2006); * Return null if the specified day doesn't exists. * * @param n Nth day to look for. * @param dayOfWeek Day to look for (Calendar.XXXDAY). * @param month Month to check (Calendar.XXX). * @param year Year to check. * @return Required Day (or null if non-existent) * @throws ArrayIndexOutOfBoundsException if dyaOfWeek parameter * doesn't represent a valid day. */ public static Day getNthOfMonth (int n, int dayOfWeek, int month, int year) throws ArrayIndexOutOfBoundsException { // Validate the dayOfWeek argument if (dayOfWeek < 0 || dayOfWeek > 6) throw new ArrayIndexOutOfBoundsException (dayOfWeek); Day first = new Day (year, month, 1); int offset = dayOfWeek - first.getDayOfWeek(); if (offset < 0) offset = 7 + offset; int dayNo = (n - 1) * 7 + offset + 1; return dayNo > first.getDaysInMonth() ? null : new Day (year, month, dayNo); }
/** * Find the first of a specific day in a given month, for instance * first Tuesday of May: * getFirstOfMonth (Calendar.TUESDAY, Calendar.MAY, 2005); * * @param dayOfWeek Weekday to get. * @param month Month of day to get. * @param year Year of day to get. * @return The requested day. */ public static Day getFirstOfMonth (int dayOfWeek, int month, int year) { return Day.getNthOfMonth (1, dayOfWeek, month, year); }
/** * Find the last of a specific day in a given month, for instance * last Tuesday of May: * getLastOfMonth (Calendar.TUESDAY, Calendar.MAY, 2005); * * @param dayOfWeek Weekday to get. * @param month Month of day to get. * @param year Year of day to get. * @return The requested day. */ public static Day getLastOfMonth (int dayOfWeek, int month, int year)
{ }
Day day = Day.getNthOfMonth (5, dayOfWeek, month, year); return day != null ? day : Day.getNthOfMonth (4, dayOfWeek, month, year);
/** * Return a scratch string representation of this day. * Used for debugging only. The format of the * day is dd/mm-yyyy * * @return A string representation of this day. */ public String toString() { StringBuffer string = new StringBuffer(); if (getDayOfMonth() < 10) string.append ('0'); string.append (getDayOfMonth()); string.append ('/'); if (getMonth() < 9) string.append ('0'); string.append (getMonth()+1); string.append ('-'); string.append (getYear()); string.append (" "); string.append (getDayName()); } return string.toString();
/** * Testing this class. * * @param args Not used. */ public static void main (String[] args) { // This proves that there are 912 days between the two major // terrorist attacks, not 911 as is common knowledge. Day september11 = new Day (2001, Calendar.SEPTEMBER, 11); Day march11 = new Day (2004, Calendar.MARCH, 11); System.out.println (september11.daysBetween (march11)); // This proves that Kennedy was president for 1037 days, // not 1000 as is the popular belief nor 1036 which is the // bluffers reply. Nerds knows when to add one... Day precidency = new Day (1961, Calendar.JANUARY, 20); Day assasination = new Day (1963, Calendar.NOVEMBER, 22); System.out.println (precidency.daysBetween (assasination) + 1); // Niel Armstrong walked the moon on a Sunday Day nielOnMoon = new Day (1969, Calendar.JULY, 20); System.out.println (nielOnMoon.getDayNumberOfWeek()); // Find last tuesdays for 2005 for (int i = 0; i < 12; i++) { Day tuesday = Day.getLastOfMonth (Calendar.TUESDAY, i, 2005); System.out.println (tuesday);
} }