CH6 – Writing Methods

  1. Create a new class named WritingMethods and add the following method named distance and main method. Just for fun, I’m showing you how I would do this on Linux from the command line. You could just as easily use notepad, or use Eclipse. By this point, use whatever you wish to use.
$ nano WritingMethods.java
  1. Add a method named distance and main.
public class WritingMethods {
  public static double distance(double x1, double y1, double x2, double y2){
    double dx = x2 - x1;
    double dy = y2 - y1;
    double dsquared = dx * dx + dy * dy;
    double result = Math.sqrt(dsquared);
    return result;
  }
  public static void main(String[] args){
    double theResult = WritingMethods.distance(3.33,2.34,4.21,4.13);
    System.out.println(theResult);
  }
}
  1. Compile and run the program. Of course, here I’m showing the command line. Feel free to use Eclipse or whatever IDE you wish.
$ javac WritingMethods.java
$ java WritingMethods
1.9946177578674065