Check if a point lies on a line

You might be familiar with the line equation ax+by+c=0. Where a,b,c are constants and x,y are the points on the line. Now let us check whether the given points lie on the given line. The program inputs the values of a,b,c and the values of x,y and then gives whether the point lies on the line or not. One of the major themes of this program is to illustrate the assertion operator.


import java.util.*;
class CheckLine
{
    public static void main(String args[])
    {

    // Create Scanner object
    Scanner s=new Scanner(System.in);

    // Enter the a,b,c
    System.out.println("Enter the a,b,c values");
    int a=s.nextInt();
    int b=s.nextInt();
    int c=s.nextInt();

    /* Note: Line equation is ax+by+c=0 */
    
    // Enter the x,y
    System.out.println("Enter the x,y planes on the line");
    int x=s.nextInt();
    int y=s.nextInt();

    // Get the expression
    boolean p=doTheyLie(a,b,c,x,y);
    
    // "lies" if p is true "does not lie" if not
    String st=p?"lies":"does not lie";
    
    System.out.println("The given point "+st+" on the line");
    }

    public static boolean doTheyLie(int a,int b,int c,int x,int y)
    {
     return a*x+b*y+c==0;
    }
}

Sample outputs of the program


Enter the a,b,c values
6
2
8
Enter the x,y planes on the line
-2
2
The given point lies on the line

Enter the a,b,c values
6
7
8
Enter the x,y planes on the line
2
0
The given point does not lie on the line

Explaining the assertion and CheckLine

return a*x+b*y+c==0; Return whether the line equation formed using this equals 0.

String st=p?"lies":"does not lie"; Set the value to the string st. If the expression p is true, then lies else does not lie is stored in st. The : expression is after the else.

No comments: