Java Exercices

fc - March 2014 - v3.0

Create a directory called java/ on your machine to host all exercices.

1. Create a Training application

package training; /** * The Training application * @author F. de Coligny - March 2014 */ public class Training { /** * Main method */ static public void main(String[] args) { // Prints to screen System.out.println("The Java training ..."); } }

Check list

in a directory called training/

class name Training.java

Compile in a terminal

Execute in a terminal

2. Create a Tree class

package training; /** * A simple tree * @author F. de Coligny - March 2014 */ public class Tree { // diameter at breast height, cm private double dbh; /** * Constructor */ public Tree (double dbh) { this.dbh = dbh; } public double getDbh () { return dbh; } public String toString () { return "Tree dbh: " + dbh; } }

Check list :

in same directory than the Training class

the instance variable is private

the methods are public

the constructor takes a dbh

the toString () method returns a String representation of the tree

test it from the Training class

Tree t1 = new Tree (5.6); System.out.println("t1: " + t1);

3. Create a SpatializedTree class

package training; /** * A tree with coordinates * @author F. de Coligny - March 2014 */ public class SpatializedTree extends Tree { // x, y of the base of the trunk (m) private double x; private double y; /** * Default constructor */ public SpatializedTree (double dbh, double x, double y) { super (dbh); setXY (x, y); } public void setXY (double x, double y) { this.x = x; this.y = y; } public double getX () {return x;} public double getY () {return y;} public String toString () { return super.toString () + " x: "+ x + " y: "+ y; } }

Check list :

this class extends Tree

its constructor calls the constructor of Tree

the toString () method relies on Tree.toString ()

test it from Training

Tree t2 = new SpatializedTree (5.6, 2, 1); System.out.println("t2: " + t2);

4. Add instance variables in the tree

private int id; // unique private int age; // years private double height; // m public int getId() { return id; } ...

Check list :

these properties must be added in Tree or in SpatializedTree ?

add the accessors for all variables : getHeight ()...

adapt the constructors and toString () methods

do we adapt only one class ?

test it from Training by adapting your code

expected result is of this kind...

5. Add methods in the tree

public double getCrownRadius () { // m return dbh / 5d; // e.g. 5cm -> 1m } public double getCrownBaseHeight () { // m return height * 2d / 3d; // e.g. 6m -> 4m }

Check list :

these methods must be added in Tree or in SpatializedTree ?

they do not rely on specific instance variables

adapt what must be adapted to get this kind of result...

use a NumberFormat to get a better result...

import java.text.NumberFormat; import java.util.Locale; ... // code example, to be adapted NumberFormat nf = NumberFormat.getInstance (Locale.ENGLISH); // decimal separator: '.' return ... + " cr: " + nf.format(getCrownRadius()) + ...

6. A method to create a list of trees

import java.util.Random; import java.util.List; import java.util.ArrayList; ... static private List createTrees(int numberOfTrees, double xSize, double ySize) { List trees = new ArrayList(); // a list Random random = new Random(); // a random generator // create trees, add them in the list for (int i = 0; i < numberOfTrees; i++) { int id = i + 1; int age = random.nextInt(25) + 1; // [0,24[ + 1 double height = age / 2d; double dbh = age; double x = random.nextDouble() * xSize; // [0,1[ * xSize double y = random.nextDouble() * ySize; Tree t = new SpatializedTree(id, age, height, dbh, x, y); trees.add(t); } // return the list return trees; }

Check list :

create a list and add trees in it

in which class do you add this method ?

use a random generator to draw random int and double numbers

test your method from the Training class...

List l = Training.createTrees(20, 50, 30); for (Object o : l) { System.out.println(o.toString ()); }

expected result of this kind...

7. Write the trees in a file

import java.io.*; ... static private void write(List trees, String fileName) throws Exception { try { // Open the file BufferedWriter out = new BufferedWriter(new FileWriter(fileName)); char tab = '\t'; double z = 0; String header = "#id" + tab + "age" + tab + "x" + tab + "y" + tab + "z" + tab + "height(m)" + tab + "dbh(cm)" + tab + "crownBaseHeight(m)" + tab + "crownRadius(m)"; // Write a line in the file out.write(header); out.newLine(); for (Object o : trees) { SpatializedTree t = (SpatializedTree) o; String line = "" + t.getId() + tab + t.getAge() + tab + t.getX() + tab + t.getY() + tab + z + tab + t.getHeight() + tab + t.getDbh() + tab + t.getCrownBaseHeight() + tab + t.getCrownRadius(); out.write(line); out.newLine(); } // Close the file out.close(); } catch (Exception e) { // in case of error System.out.println("Could not write in file: " + fileName); throw e; // send the exception to the caller } }

Check list :

if error, the method writes a message AND throws an exception

the caller method : main () now throws an exception

after each line, a newLine must be written

the columns are separated by tabs

the header line starts with a « # »

where is located the file trees.txt ?

test this method after the tree list creation in the Training class...

String fileName = "trees.txt"; write (l, fileName); System.out.println ("Wrote the tree list in " + fileName);

resulting file (extract)...

8. Pass parameters on the command line

/** * Main method 4 expected arguments: numberOfTrees, xSize, ySize, fileName */ static public void main(String[] args) throws Exception { for (int i = 0; i < args.length; i++) { System.out.println("args["+i+"]: "+args[i]); } int numberOfTrees = 20; double xSize = 50; double ySize = 30; String fileName = "trees.txt"; try { if (args.length != 4) throw new Exception(); numberOfTrees = new Integer (args[0]).intValue (); xSize = new Integer (args[1]).intValue (); ySize = new Integer (args[2]).intValue (); fileName = args[3]; } catch (Exception e) { System.out.println("Training expects 4 arguments: numberOfTrees, xSize, ySize, fileName"); return; // stops the program } // Prints to screen System.out.println("The Java training ..."); // Tree t1 = new Tree(1, 5, 3.5, 5.6); // System.out.println("t1: " + t1); // Tree t2 = new SpatializedTree(2, 6, 6.7, 6.1, 4, 3); // System.out.println("t2: " + t2); List l = Training.createTrees(numberOfTrees, xSize, ySize); for (Object o : l) { System.out.println(o.toString()); } write(l, fileName); System.out.println("Wrote the tree list in " + fileName); }

Check list :

check that all expected arguments are there

transform the Strings into numbers

in case of trouble, explain and stop the program

change the literal values by the given variables

expected result of this kind...