Charge.java


This is the syntax highlighted version of Charge.java from 3.2 Creating Data Types of
Introduction to Computer Science by Robert Sedgewick and Kevin Wayne.

import java.awt.Color;

public class Charge {
    private static double k = 8.99E09;               // electrostatic constant (N m^2 / C^2)

    private double x, y;    // position
    private double q;       // charge

    public Charge(double x, double y, double q) {
        this.x = x;
        this.y = y;
        this.q = q;
    }

    // return the potential
    public double potential(double x, double y) {
        return k * q / distanceTo(x, y);            // V = kq / r
    }

    public double fieldX(double x, double y) {
        double dx = x - this.x;
        double r = distanceTo(x, y);
        double E = k * q / (r * r);                 // E  = kq / r^2
        return E * dx / r;                          // Ex = E * dx / r
    }

    public double fieldY(double x, double y) {
        double dy = y - this.y;
        double r = distanceTo(x, y);               
        double E = k * q / (r * r);                 // E  = kq / r^2
        return E * dy / r;                          // Ey = E * dy / r
    }

    // Euclidean distance between this Charge and (x, y)
    public double distanceTo(double x, double y) {
        double dx = x - this.x;
        double dy = y - this.y;
        return Math.sqrt(dx*dx + dy*dy);
    }

    // is this charge positive?
    public boolean isPositivelyCharged() { return (q > 0); }

    // return x and y coordinates of this charge
    public double getX() { return x; }
    public double getY() { return y; }

    // return string representation of this charge
    public String toString() {
        return "x = " + x + "  y = " + y + "  q = " + q;
    }

}


Last updated: Wed Jul 28 15:43:49 EDT 2004 .
Copyright © 2004, Robert Sedgewick and Kevin Wayne.