/* SimpleExample/Ant.java A very simple class, with four fields: ID weight x, y */ import java.util.Random; // Only the Random class public class Ant { // class variables ("static") private static int nextID = 0; // next ID to assign to ants private static Random rng; // pointer to rng given to us // instance variables int ID; // these have the default access double weight; // "package private" int x, y; // see Access controls in java books // constructors Ant () { // create with defaults provided ID = nextID++; weight = 0.0; x = 0; y = 0; } Ant ( int X, int Y, double wt ) { // constructor with parameters ID = nextID++; weight = wt; x = X; // note case matters! x != X y = Y; } ///////////////////////////////////////////////////////////////////////////////// // doSomething -- silly method... public double doSomething ( int i ) { double returnValue = 0; double d = 20; // i'd recommend better names than this!! int j; // Here we send the printf message to the PrintStream object referenced by // the "out" field of the System class! See System in Java API, // and see the printf method of the PrintStream class for details // on formatting the output. (Its bascially following c printf rules.) System.out.printf( "Ant ID=%d (wt=%.2f) sent doSomething():\n", ID, weight ); if ( ID % 2 == 0 && weight > 10.0 ) returnValue = (weight + i) / d; else returnValue = getUniformRandomFractionOf( weight ); System.out.printf( " --> returnValue=%.3f --> ", returnValue ); // this next is just an example of casting of data types -- see Java books j = (int) d; // tell java to convert the double d into an int return returnValue; } // getUniformRandomFractionOf // returns a random fraction of the parameter sent to in public double getUniformRandomFractionOf ( double d ) { System.out.printf( " - Ant ID=%d sent getUniformRandomFractionOf( %.3f ):", ID, d ); double rvalue; double r = rng.nextDouble(); System.out.printf( " -> r = %.5f\n", r ); rvalue = r * d; return rvalue; } public void printSelf () { System.out.printf( "ID = %d, x=%d, y=%d, weight = %.2f\n", ID, x, y, weight ); } ///////////////////////////////////////////////////////////////////////////////// // accessors (getters/setters) public static void setRng ( Random r ) { rng = r; } // for the class variable! public int getID () { return ID; } // no setter -- no others can cnage it. public double getWeight () { return weight; } public void setWeight ( double wt ) { weight = wt; } // NB -- no set/get-X or -Y !! }