Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Separate Classes must be in the same directory as main method or must invoke
- classpath
- */
- public class Charge {
- //first declare instance variables which are usually private
- private final double rx;
- private final double ry;
- private final double q;
- /* A class contains constructors that are invoked to create objects from a
- class blueprint. Constructor declarations look like method declarations
- -except that they use the name of the class and have no return type.
- Constructor must be capitalized. Classes and Constructors are capitalized
- methods are not.
- */
- //Constructor
- public Charge(double x0, double y0, double q0) {
- rx = x0;
- ry = y0;
- q = q0;
- }
- /*
- The method to compute electrical potential which is defined by the equation
- V = kq/r
- */
- public double potentialAt(double x, double y){
- double k = 8.99e09; //Electrostatic Constant that k=8.99 X 10^9 Nm^2/C^2 (N = Newtons, m = meters, C = Coloumbs)
- //r = delta x - delta y
- double dx = x - rx; //delta x for distance
- double dy = y - ry; //delta y for distance
- return k*q/Math.sqrt(dx*dx + dy*dy);//computation using distance formula
- }
- }
- Charge(double x0, double y0, double q0)
- double potentialAt(double x, double y)
- String toSting()
- 1. Create an object
- ClassName object = new ClassName (invoke Constructor)
- --------- ------ --- --------- -----------------
- Charge C = new Charge (2.2, 3.4, 7.2)
- 2. Use instance methods on object
- C.potentialAt(2.3, 4.2)
- import java.util.*;
- public class ChargeClient {
- public static void main(String[] args) {
- //Using a scanner object to get values
- System.out.println("Please enter an X Value");
- Scanner in = new Scanner(System.in);
- // get values from command line for x and y
- double x = in.nextDouble();
- System.out.println("Please enter a Y Value");
- double y = in.nextDouble();
- /*
- 1. Instantiate objects C1 and C2
- ClassName object = new ClassName (invoke Constructor)
- --------- ------ --- --------- -----------------
- Charge C = new Charge (2.2, 3.4, 7.2)
- 2. we are invoking constructor from API
- Charge(double x0, double y0, double q0)
- */
- Charge c1 = new Charge(.51, .63, 21.3);
- Charge c2 = new Charge(.13, .94, 81.9);
- //print out charge so we know what we are dealing with
- System.out.println(c1);
- System.out.println(c2);
- /*
- Here we create variables to hold the return from our potential method
- which is enacted on our C1 and C2 objects.
- 1. We call a method on an object by:
- objectName.methodName(appropriate parameters)
- */
- double v1 = c1.potentialAt(x, y);
- double v2 = c2.potentialAt(x, y);
- //Concatenate results and print them out.
- System.out.println(v1+v2);
- System.out.println("this is the printf statement");
- System.out.printf("%.2En", v1+v2);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement