advertisement
javaboutique
Search Tips
Articles  |   Tutorials  |   Reviews  |   Tools  |   by Category  |   by Date  |   by Name  |   Submit  |   Source  |   Forums  |  
javaboutique
Browse DevX


Partners & Affiliates











advertisement

DueDateCalculator



/*

 * This program is a modification of a Sun Microsystems example program.

 * It is intented as a demonstration of a Java program and not as a serious clinical tool.

 * It has not been completely tested.

 * This is my first crack at Java so please don't take it as good style

 * 

 * The developmental comments were adapted from 

 * "The developing human" 3rd Edition by Keith L. Moore.

 *

 * Randy Giffen, Jan 1996

 * rgiffen@fox.nstn.ca

 *

 * Copyright (c) 1994 Sun Microsystems, Inc. All Rights Reserved.

 *

 * Permission to use, copy, modify, and distribute this software

 * and its documentation for NON-COMMERCIAL purposes and without

 * fee is hereby granted provided that this copyright notice

 * appears in all copies. Please refer to the file "copyright.html"

 * for further important copyright and licensing information.

 *

 * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF

 * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED

 * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A

 * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR

 * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR

 * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.

 */



/* This program could use some layout work, and the functionality

 * could use some tweaking, but it seems to basically work.

 */



import java.awt.*;

import java.util.*;

import java.applet.Applet;



public class DueDateCalculator extends Applet {

    Frame window;

    DatePanel LMPPanel;

    TextArea outputArea;

    String days[] = new String[31];

    String years[] = new String[10];

    String months[] = new String[12];



    public void init() {



	years[0] = "1995";

	years[1] = "1996";

	years[2] = "1997";

	years[3] = "1998";

	years[4] = "1999";

	years[5] = "2000";

	years[6] = "2001";

	years[7] = "2002";

	years[8] = "2003";

	years[9] = "2004";



	months[0] = "January";

	months[1] = "February";

	months[2] = "March";

	months[3] = "April";

	months[4] = "May";

	months[5] = "June";

	months[6] = "July";

	months[7] = "August";

	months[8] = "September";

	months[9] = "October";

	months[10] = "November";

	months[11] = "December";



	LMPPanel = new DatePanel(this, "First day of Last Period: ", months, years);

	outputArea = new TextArea();

	outputArea.setEditable(false);



        	setLayout(new BorderLayout(10,10));

       	add("North", LMPPanel);

        	add("Center", outputArea);

	add("South", new Label("Disclaimer - This program is a Java demonstration only and not a reliable clinical tool.", Label.CENTER));

    }



    public void start() {

	resize(550,400);

    }



    /* Respond to user actions. */

    public boolean handleEvent(Event e) {

	if (e.target instanceof Button) {

	   newOutputText();	     	

	   return true;

	} 

	return false;

    }



    public void newOutputText() {

    /* Called when the user presses the calculate button.

     * Check the date and update the text area

     */ 

	Date LMPDate;

	Date dueDate;

	Date today = new Date();

	Date errorDate = new Date();

	String tempString;

	String weight;

	String length;

	int age;	

	int weeks;



	LMPDate = LMPPanel.getDate();

	if (LMPDate.getYear()  == 50) {

		outputArea.setText("Invalid date. Try again");

		return;

	}

	dueDate = calcDueDate(LMPDate);

	tempString = dueDate.toString();

	outputArea.setText("The predicted due date (EDC) ");

	if (today.before(dueDate)) {

		outputArea.appendText("is: ");

	} else {

		outputArea.appendText("was: ");

	}

	outputArea.appendText(tempString.substring(0, 10));

	outputArea.appendText(", " + tempString.substring(21) + ".\n");

		

	age = calcGestationalAge(LMPDate);

	if ((age >= 21) && (age <= 308)) {	//add info if currently pregnant

		weeks = age / 7;

		outputArea.appendText("Estimated gestational age: " + Integer.toString(age) + " days (");

		outputArea.appendText(Integer.toString(weeks) + " weeks)\n\n");

		weight = weightForWeek(weeks);

		if (weight != "") {

			outputArea.appendText("Current weight: " + weight + " grams\n");

		}

		length = lengthForWeek(weeks);

		if (length != "") {

			outputArea.appendText("Current length: " + length + " centimeters\n\n");

		}

		outputArea.appendText(commentsForWeek(weeks));

	}

	return;

    } 



    private static int mlength[] = {

	31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31

    };



    Date calcDueDate(Date LMPDate) {

    /*

     * Calculate the due date as 280 days from the LMP

     * The fact that 2000 is a leap year makes the algorithm slightly simpler

     */

	Date dueDate = new Date();

	int day = LMPDate.getDate();

	int month = LMPDate.getMonth();

	int year = LMPDate.getYear();	

	int daysInMonth;

 

	// Add 280 days

	day = day + 280;

	daysInMonth = mlength[(month)];

	if ((month == 1) && (year%4 == 0)) {

		daysInMonth = 29;   //leap year

	}

	while (day > daysInMonth) {

		month = month + 1;

		if (month == 12) {

			month = 0;

			year = year + 1;		

		}

		daysInMonth = mlength[(month)];

		if ((month == 1) && (year%4 == 0)) {

			daysInMonth = 29;   //leap year

		}

		day = day - daysInMonth;

		// System.out.println(Integer.toString(day));

	}

	dueDate = new Date(year, month, day);

	return(dueDate);

    }



    int calcGestationalAge(Date LMPDate) {

    /*

     * Calculate the Gestational age using LMPDate and today's date. 

     * Return 0 if LMP hasn't come yet.

     */

	Date todayDate = new Date();

	int days;

	int day = LMPDate.getDate();

	int month = LMPDate.getMonth();

	int year = LMPDate.getYear();	

	int todayDay = todayDate.getDate();

	int todayMonth = todayDate.getMonth();

	int todayYear = todayDate.getYear();	



	if (LMPDate.after(todayDate)) {

		return(0) ;

	}



	// Count the Days

	days = 0;

	while ((year < todayYear) || (month < todayMonth) || (day < todayDay)) {

		days = days + 1;

		day = day + 1;

		if (day > mlength[month]) {

			if ((month == 1) && (day == 29) && (year%4 == 0)) {

			                    //29 Feb, leap year so let it go by

			} else {

				day = 1;

				month = month + 1;

				if (month == 12) {

					month = 0;

					year = year + 1;

				}

			}		

		}

	}

	return(days);

    }



    private static String dComment[] = {

	"","","",

	"Ovulation usually occurs by now.",//3

	 "Implantation in the wall of the uterus.\nPrimitive placental circulation established.",  

	"First missed menstral period.\nBrain begins to form.",

	"Heart begins to beat.\nArm and leg buds present.", 

	"Eyes developing.",

	"Mouth and nose forming.\nArms bent at elbow.", 

	"Eyelids beginning.\nTrunk elongating and straightening.",//9

	"Fingers distinct.\nBeginnings of all essential external and internal structures are present.",

	"Eyes closing or closed.\nHead more rounded.\nExternal genitalia still not distinguished as male or female.\nIntestines in umbilical cord.", 

	"Facehas human profile.\nIntestine in abdomen.\nEarly fingernail development.",    //12

	"","Sex distinguishable externally.\nWell-defined neck." ,

	"","Head erect.\nLower limbs well developed." ,

	"","Ears stand out from head.",

	"","Vernix caseosa present.\nEarly noenail development." ,

	"","Head and body hair (lanugo) visible."  ,

	"","Skin wrinked and red." ,

	"","Fingernails present.\nLean Body." ,

	"","Eyes partially open.\nEyelashes present." ,

	"","Eyes open.\nSkin slightly wrinked." ,

	"","Toenails present.\nBody filling out.\nTestis descending in males.", 

	"","Fingernails reach finger tips.\nSkin pink and smooth.", //34

	"","","","Body usually plump.\nLanugo hairs almost absent.\nToenails reach toe tips.\nFlexed limbs, firm grasp.",  

	"","Full term.\nProminent chest, breasts protrude.\nFingernails extend beyond finger tips.", //40

	"","Overdue",

	"Overdue",  

	"Overdue","",""

    };



    public String commentsForWeek(int week) {

	return(dComment[week]);

    }



    private static String dWeight[] = {

	"","","","","","","",

	"0.5", "1", "2",  "5",  "10", "20",  "35", "60", "85", "120","160", "220",

 	"270", "330",  "395",  "460", "540", "650", "740", "850",  "960",

	"1100",  "1240", "1420",   "1560", "1750",   "1900", "2080", "2260",

	"2420", "2640",   "2900", "3050", "3250", "", "" ,"", "", ""

    };





    public String weightForWeek(int week) {

	return(dWeight[week]);

    }



    private static String dLength[] = {

	"","","","","","","",

	"2",  "4",  "5", "6", "7", "9", 

	"10",  "12", "14",  "16", "18", "20",

	"22", "25",  "26",  "28",  "29", "30",  

	"31",  "32",  "33",  "35",  "36", "38",

	"39",  "40",  "41",  "42",  "43", "45", 

	"46",  "48", "49", "50","","","","",""

    };



    public String lengthForWeek(int week) {

	return(dLength[week]);

    }







    public static void main(String args[]) {

	Frame f = new Frame("Due Date Calculator");

	DueDateCalculator calculator = new DueDateCalculator();



	calculator.init();



	f.add("Center", calculator);

	f.pack();

	f.show();

    }

}





class DatePanel extends Panel {

    String title;

    Label label;

    TextField dayField;

    Choice dayChooser;	

    Choice monthChooser;

    Choice yearChooser;

    Button calcButton;

    int min = 0;

    int max = 10000;

    DueDateCalculator controller;

    Panel bottomPanel = new Panel();

    String years[];

    String months[];



 

    DatePanel(DueDateCalculator myController, String myTitle, String myMonths[], String myYears[]) {

	super();

	controller = myController;

	title = myTitle;

	months = myMonths;

	years = myYears;



	//Add the label

	label = new Label(title, Label.LEFT);

	add(label);



	//Add the text field

	dayField = new TextField("1", 5);

	dayField.setEditable(true);

	bottomPanel.add(dayField);





	//Add the pop-up lists (Choice)

	monthChooser = new Choice();

	for (int i = 0; i < months.length; i++) {

	    monthChooser.addItem(months[i]);

	}

	bottomPanel.add(monthChooser);



	yearChooser = new Choice();

	for (int i = 0; i < years.length; i++) {

	    yearChooser.addItem(years[i]);

	}

	bottomPanel.add(yearChooser);



	//Add the button

	calcButton = new Button("Calculate");

	bottomPanel.add(calcButton);

	

	add(bottomPanel);

    }



    private static int mlength[] = {

	31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31

    };



    Date getDate() {

    /* 

     * Get the date from the data entry widgets.

     * Return a date with a year of 50 for invalid data

    */

	Date errorDate = new Date();

	Date LMPDate = new Date();

	int day;

	int month;

	int year;	



	// Get date of LMP

   	errorDate.setYear(50);

	try {

	    day = Integer.valueOf(dayField.getText()).intValue(); 

	} catch (java.lang.NumberFormatException e) {

   	    return(errorDate);

	}

	month = monthChooser.getSelectedIndex();

	year = yearChooser.getSelectedIndex() + 95;



                    //Check the day according to the month (i.e. no Feb 30th)

	if ((day < 1) || (day > mlength[month])) {

		if ((year%4 == 0) && (month == 1) && (day == 29)) {

			//let it go (Feb 29)

		} else {

			return(errorDate);

		}

	}	

	LMPDate = new Date(year, month, day);

	return(LMPDate);

    }

}


How to Add Java Applets to Your Site

New on the Java Boutique:

New Review:

Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling API boasts simplicity, ease-of-integration, a well-rounded feature set, and it's free!

New Applet:

Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA sequences into three useful formats.

Elsewhere on internet.com:

WebDeveloper Java
Lots of Java information on webdeveloper.com

WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.

ScriptSearch Java
Hundreds of free Java code files to download.

jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.

 Intel Go Parallel Portal
 Internet.com eBook Library
 IBM Software Construction Toolbox
 Microsoft RIA Development Center
 Destination .NET
XML error: not well-formed (invalid token) at line 43
advertisement
Receive Articles via our XML/RSS feed
Receive Articles via our XML/RSS feed

JavaBytes
Internet Cyclone
This powerful, easy-to-use, internet optimizer is for Windows 95, 98, ME, NT, 2000 and XP. It's designed to automatically optimize your Windows settings, boosting your Internet connection up to 200%.

Google Hopes Chrome Will Help, Not Hurt Firefox
Remember Figlets? They're Back With Zend
Microsoft Readies an App Store Competitor?
Google: Chrome Browser Will Make Money
Sam Ramji: Microsoft's Man in Open Source
Google to Shake Up Browsers With Own Launch
Mozilla's Ubquity Mashup: For The Masses?
iPhone Users Just Want to Have Fun
Oops! I Fixed the Linux Kernel
Jim Zemlin: The New Center of Linux Gravity

Code Around C#'s Using Statement to Release Unmanaged Resources
Writing Functional Code with RDFa
BitLocker Brings Encryption to Windows Server 2008
Network Know-How: Exploring Network Algorithms
Create a Durable and Reliable WCF Service with MSMQ 4.0
The Baker's Dozen: 13 Tips for SQL Server 2008 and SSRS 2008
Book Excerpt: Microsoft Expression Blend Unleashed
Develop a Mobile RSS Feed the Easy Way
State of the Semantic Web: Know Where to Look
A 3D Exploration of the HTML Canvas Element

Advertising Info  |   Member Services  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Intel PDF: Virtualization Delivers Data Center Efficiency
Intel eBook: Managing the Evolving Data Center
Microsoft Article: BitLocker Brings Encryption to Windows Server 2008
Symantec eBook: The Guide to E-Mail Archiving and Management
Microsoft Article: RODCs Transform Branch Office Security
Go Parallel Article: James Reinders on the Intel Parallel Studio Beta Program
Avaya Article: Advancing the State of the Art in Customer Service
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
Avaya Article: Avaya AE Services Provide Rapid Telephony Integration with Facebook
Go Parallel Article: Getting Started with TBB on Windows
HP eBook: Storage Networking , Part 1
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Seminar: Efficiencies in Hardware/Software Virtualization
HP Webcast: Disaster Recovery Planning
Go Parallel Video: Performance and Threading Tools for Game Developers
HP Video: StorageWorks EVA4400 and Oracle
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
IBM TCO eKIT: Your IT Budget is Under Attack, Get in Control
IBM Energy Efficiency eKIT: Learn How to Reduce Costs
30-Day Trial: SPAMfighter Exchange Module
Red Gate Download: SQL Toolbelt and free High-Performance SQL Code eBook
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
Microsoft Article: Silverlight Streaming--Free Video Hosting for All
Featured Algorithm: Intel Threading Building Blocks - parallel_reduce
HP Demo: StorageWorks EVA4400
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES