Java – Program To Calculate Distance Between Two Points

Java – Program To Calculate Distance Between Two Points

 

The distance between two points formula derived from the Pythagorean Theorem.

To find the distance between two points (x1,y1) and (x2,y2), all that you need to do is use the coordinates of these ordered pairs and apply the formula pictured below:

import java.lang.Math.*;
class DistanceBetweenPoints
{
	public static void main(String arg[])	
	{
            int x1,x2,y1,y2;
	    double distance;
	    x1=1;y1=1;x2=4;y2=4;
	    distance=Math.sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));	 	    
            System.out.println("distance between"+"("+x1+","+y1+"),"+"("+x2+","+y2+") : "+distance);
	}
}

Taking input through scanner class

import java.util.Scanner;
class DistanceBetweenPoints
{
	public static void main(String arg[])
	
	{
	
             	 int x1,x2,y1,y2;
 
	         double distance;
	
	         Scanner sc=new Scanner(System.in);
 
	         System.out.println("Enter x1 point");
	   
                 x1=sc.nextInt();
	    
                 System.out.println("Enter y1 point");
	   
                 y1=sc.nextInt();
 
	         System.out.println("Enter x2 point");
	   
                 x2=sc.nextInt();
 
	         System.out.println("Enter y2 point");
	   
                 y2=sc.nextInt();
	  	    
		 distance=Math.sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));
 	 	    	 	    
  	         System.out.println("distance between"+"("+x1+","+y1+"),"+"("+x2+","+y2+") : "+distance);
 
	}
 
}

Taking inputs through command line arguments.

import java.util.Scanner;
class DistanceBetweenPoints
{
	public static void main(String args[])
	
	{     	long x1,x2,y1,y2;
 
		double distance;
 
                x1=Long.parseLong(args[0]);
		
                y1=Long.parseLong(args[1]);
 
	        x2=Long.parseLong(args[2]);
		
                y2=Long.parseLong(args[3]); 
		     
	        distance=Math.sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));
 	 	        
  	        System.out.println("distance between"+"("+x1+","+y1+"),"+"("+x2+","+y2+") : "+distance);
 
	}
}

Posted

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *