Check whether a point lies within a given circle using java

                          Hello guys, this a very interesting yet simple concept. Here what we are going to learn is to check whether a point lies inside a given circle or not. Here we will use BufferedReader to take inputs and compare between the two inputs. The result value we will display in the output.
Sample Output:



Program Code:

import java.io.*;
class Circle
{
 double x, y;
 double radius;
 Circle(double x1,double y1, double radius)
 {
  x=x1; y=y1;
  this.radius=radius;
 }
    
 void check(double x2, double y2)
 {
  
  double d1=Math.sqrt((x-x2)*(x-x2)+(y-y2)*(y-y2));
  if (radius>d1)
  {
   System.out.println("the point lies inside circle with "+x+","+y+" as centre");
  }
  else
   System.out.println("the point doesnt lie inside the circle with "+x+","+y+" as centre and "+radius+" as radius");

 }

 public static void main(String[] args) throws Exception
 {
  BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
  System.out.println("Enter circle details");
  System.out.println("---------------------");
  System.out.print("Enter x co-ordinate:");
  String val1=br.readLine();
  System.out.print("Enter y co-ordinate:");
  String val2=br.readLine();
  System.out.println("Enter radius:");
  String val3=br.readLine();
  
  double xx=Integer.parseInt(val1);
  double yy=Integer.parseInt(val2);
  double rr=Integer.parseInt(val3);

  System.out.println("The circle you have entered is having centre at ("+xx+","+yy+") and radius="+rr);

  Circle c=new Circle(xx,yy,rr);
  
  System.out.println("Enter the point you want to check");
  System.out.print("x co-ordinate:");
  String val4=br.readLine();
  System.out.print("y co-ordinate:");
  String val5=br.readLine();
                double a=Integer.parseInt(val4);
  double b=Integer.parseInt(val5);
  c.check(a,b);
 }
}

Description:
                       Well as you guys see, this concept receives input of one circle with its center and the radius value and another point co-ordinates, which we have to compare and tell that the point lies inside the circle or not. For that we can use a very simple concept. First we will calculate the distance of the given point with the center of the circle which I have done by using formula d2=Math.sqrt((x-x2)*(x-x2)-(y-y2)*(y-y2)) . After this we have to compare it with the radius value. If it is less than the radius value, then it is inside the circle, otherwise it is not inside the circle.
                 


                                   Well that's it for now guys. Hope you liked the concept. If you find some bugs or have queries then write in the comments section below or you can contact me through my profile. And kindly subscribe to our website, its totally free!!
Keep coding, Thank you.

Comments

Popular posts from this blog

Non Restoring Division Algorithm Implementation in C

Hackerrank Modified Kaprekar Numbers Solution

Bit Stuffing Code Implementation in Java