Matt Gerrans
Posts: 1153
Nickname: matt
Registered: Feb, 2002
|
|
Re: Creating a Method
|
Posted: Jan 29, 2003 9:07 PM
|
|
/**
* MyDate.java
*
* Simple demo of methods in a class.
*
* Copyright 2003, Matt Gerrans.
*
* Turning in this code as homework is a violation of ethical principals,
* and punishable by severe penalties, even if you change the variable
* names.
*/
public class MyDate
{
private int year;
/**
* This is the constructor, which will set up the year value for this
* object.
*/
public MyDate( int y )
{
year = y;
}
/**
* Here is the isLeapYear() method, which you can call to find out
* whether this instance of the MyDate object is a leap year.
*/
public boolean isLeapYear()
{
boolean isLeap = false;
// Here is my somewhat questionable method of determining whether
// the year is a leap year:
isLeap = ((new java.util.Random()).nextInt(2) == 0 ? true : false);
// Instead of my technique, you will want to replace it with your code
// to check whether the year is really a leap year; if it is, change
// isLeap to true.
return isLeap;
}
/**
* I also added this toString() method, to facilitate displaying
* information about the object at runtime.
*/
public String toString()
{
return Integer.toString(year);
}
/**
* This the the static (static means there is only one) entry point.
* It should not be heavily used for any kind of activity specific
* to your class. Here it is just used as kind of a quick demo
* of using the MyDate class.
*/
public static void main( String[] args )
{
int year = 1972;
// Your code here to read the year from the keyboard, or wherever.
// I'll just read it from the command line, if a parameter was
// specified. I am foolishly throwing caution to the wind and
// assuming that the parameter, if specified, will be a nicely
// formed integer value. This will probably be the case, one in
// ten times and more often than not, this program will crash with
// an ugly stack trace about some crazy thing called a
// NumberFormatException and the user will curse my lazy bones.
if( args.length > 0 )
year = Integer.parseInt(args[0]);
// Before you can use your MyDate object, you must create an instance
// of it, with "new" and initialize it with the year value from above:
MyDate myDate = new MyDate( year );
if( myDate.isLeapYear() )
System.out.println( myDate.toString() + " is a leap year." );
else
System.out.println( myDate.toString() + " isn't a leap year." );
}
}
|
|