// Scott DeRuiter 7/1/2002
// Line.java
// A Line class to be used by other programs.
public class Line
{
// Data members for a line.
private double x1, y1, x2, y2;
// A constructor that takes two ordered pairs.
public Line ( double firstx, double firsty, double secondx, double secondy )
{
x1 = firstx;
y1 = firsty;
x2 = secondx;
y2 = secondy;
}
// A constructor for default line, y = x
public Line ( )
{
x1 = 0.0;
y1 = 0.0;
x2 = 1.0;
y2 = 1.0;
}
// This is a method to find the slope.
public double Slope ( )
{
return ( ( y2 - y1 ) / ( x2 - x1 ) );
}
// A method to find the y-intercept.
public double Yint ( )
{
return ( y1 - ( ( y2 - y1 ) / ( x2 - x1 ) ) * x1 );
}
// This method prints the equation of the line using the previous two methods.
public void PrintLine ( )
{
System.out.print ( "y = " + Format.right ( Slope ( ), 8, 3 ) );
System.out.println ( "x + " + Format.right ( Yint ( ), 8, 3 ) );
}
}
// Scott DeRuiter 7/1/2002
// LineClient.java
// Uses the Line class to get and print info about a line.
// 7/15/2011 - Greenstein: Changed TextReader to Scanner
import java.util.Scanner;
public class LineClient
{
public static void main ( String [] args )
{
double xone, yone, xtwo, ytwo;
Scanner keyboard = new Scanner ( );
System.out.print ( "Enter x1: " );
xone = keyboard.nextDouble ( );
System.out.print ( "Enter y1: " );
yone = keyboard.nextDouble ( );
System.out.print ( "Enter x2: " );
xtwo = keyboard.nextDouble ( );
System.out.print ( "Enter y2: " );
ytwo = keyboard.nextDouble ( );
Line myline = new Line ( xone, yone, xtwo, ytwo );
myline.PrintLine ( );
Line myline2 = new Line ( );
myline2.PrintLine ( );
}
}
Back to Lesson 4 Examples
Back to Java Main Page