2. Java Object-Oriented (7)_Encapsulation Ideas - Judging the Relationship between Points and Circles

2018-05-01

 

Determine the relationship between points and circles

 

Determine the relationship between a point and a circle

  1) Outside the circle

  2) On the circle

  3) Inside the circle

 

  Translated into code: general nouns are either objects or states; verbs are methods

  

Idea: Compare the radius and the distance between two points

 

 Code:

 

1  // Abstract the point object into class 
2  class Points
 3  {
 4      private  int x; // abscissa 
5      private  int y; // ordinate 
6  
7      Points( int x, int y){
 8          this .x = x;
 9          this .y = y;
 10      }
 11      
12      // get method 
13      public  int getX(){
 14          return x;    
 15      }
 16     public  int getY(){
 17          return y;    
 18      }
 19      // set method 
20      public  void setX( int x){
 21          this .x = x;
 22      }
 23      public  void setY( int y){
 24          this .y = y ;
 25      }
 26  
27  }
 28  // Abstract the circle as an object 
29  class Circle
 30  {
 31      private  int r;// Radius 
32      
33      Circle( int r){
 34          this .r = r;
 35      }
 36  
37      /* 
38          Judging the relationship between the point and the circle
 39              Parameters: The object of the point to be judged
 40              Returns: 
 41                  1:
 42                  0 outside the circle : on the circle
 43                  -1: on the circle
 44          
45      */ 
46      public  int jude(Points p){     //   public int means to return a value of type int
 47          // sum of squares of x plus sum of squares of y 
48          intxxyy = p.getX() * ​​p.getX() + p.getY() * p.getY();
 49          int rr = this .r * this .r;
 50  
51          if (rr > xxyy){
 52              System. out.println("The point is inside the circle" );
 53              return -1; // End the method while returning the value 
54          } else  if (rr < xxyy){
 55              System.out.println("The point is outside the circle" );
 56              return 1 ;
 57          } else {
 58              System.out.println("The point is on the circle" );
59              return 0 ;
 60  
61              }
 62      
63      }
 64  }
 65  
66  
67  
68  
69  // Determine the relationship between point and circle 
70  class PointDemo 
 71  {
 72      public  static  void main(String[] args) 
 73      {
 74          // Create a point object (3,4) 
75          Points p = new Points(3,4 );
 76          
77          // Create an object with a radius of 5 
78          Circle c = new Circle(5);
 79  
80          // call method 
81           int ret = c.jude(p);
 82          // print result 
83          System.out.println(ret);
 84      }
 85 }

 

 Output result:

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325117702&siteId=291194637