CSCI A201/A597

Lab Notes 10

Spring 2000


Getting help with homework assignment 8 (eight).

The assignment asks you to define some procedures (methods).

First solve the problem by itself.

Then turn your solution into a procedure.

For example: computing the distance between two points.

How do you solve it?

Here's a picture:

An implementation:

import element.*;

public class Test {
    public static void main(String[] args) {
	Pt p, q; 
	p = new Pt(2, 4); 
        q = new Pt(6, 1); 
        double distance; 
        int h, v; 
        h = Math.abs(p.x() - q.x()); 
	v = Math.abs(p.y() - q.y()); 
	distance = Math.sqrt(h * h + v * v); 
	System.out.println(distance); 
    } 
} 
Then we isolate the part that calculate the distance and place it in a method.

import element.*;

public class Test {
    public static void main(String[] args) {
	Pt p, q; 
	p = new Pt(2, 4); 
        q = new Pt(6, 1); 
        double distance; 
        distance = Library.computeDistanceBetween(p, q); 
	System.out.println(distance); 
    } 
} 

class Library {
    public static double computeDistanceBetween(Pt p, Pt q) {  
        // There was a typo here thanks to Jason Levy for catching it!
        int h, v;
        h = Math.abs(p.x() - q.x()); 
	v = Math.abs(p.y() - q.y()); 
	return Math.sqrt(h * h + v * v); 
    }
}
When we create a method we follow these steps:

  1. Write and test the code that implements the procedure.
    We've done this in Test.java
  2. Identify what the code needs (inputs) and what it produces (outputs).
    Our procedure needs the two points. It should have as the result the distance between the two points, most likely a number with decimals.
  3. The inputs are called parameters, and they have to be listed as formal parameters. The have types. Their number and order are important. They should be given names, used in the definition of the procedure.
    We call the parameters, the two points, p and q. Their type is Pt.
  4. Come up with a descriptive name for the procedure (or method). The name of the procedure together with the number and types of the parameters (in the order in which they are listed) is called the signature of the method. There cannot be two methods with the same signature in the same class.
    We decided to call it computeDistanceBetween. Other names are possible.
  5. If the method returns a result, make sure you specify that in the definition of the method. Otherwise mark it as void (that is, as not returning a result).
    Our method returns a double.

This is one of the 12 parts of assignment 8. (This is #5).

Expect to see more help posted here on assignment 8.


Last updated Mar 23, 2000 by Adrian German more to come soon.