Java Function distance that calculates the distance between two points (x1, y1) and (x2, y2). All numbers and return values should be of type double.

//Java Function distance that calculates the distance between two points (x1, y1) and (x2, y2). All numbers and return values should be of type double.


import java.util.Scanner;
import java.lang.Math;

public class Program 
{   
    public static void main( String[] args ) 
    {
		Scanner reader = new Scanner(System.in);
		int x1,x2,y1,y2;
  		double r=0;
  		System.out.print("\nTwo Points (x1,x2) & (y1,y2) : \n");

 	 	System.out.println("Enter x1:");
 	 	x1 = reader.nextInt();
  
 	 	System.out.println("Enter x2:");
 	 	x2 = reader.nextInt();
  
 	 	System.out.println("Enter y1:");
  		y1 = reader.nextInt();
  
  		System.out.println("Enter y2:");
 	 	y2 = reader.nextInt();
	  
 	 	r=findDistance(x1,y1,x2,y2);
  	 	System.out.print("Distance between the 2 points is " + r );
   	}
   	public static double findDistance(int x1, int y1, int x2, int y2)
   	{
		
    		double d;
  		d=Math.sqrt((Math.pow(x2-x1,2))+(Math.pow(y2-y1,2)));
  		return d;
   	}
	
}

Output :
Two Points (x1,x2) & (y1,y2) :

Enter x1:
1
Enter x2:
2
Enter y1:
3
Enter y2:
4
Distance between the 2 points is 1.414214



Leave a comment