fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. Scanner in = new Scanner( System.in);
  13. double p1x, p1y, p2x, p2y; //point
  14. double x, y; //intersection points
  15. double cx, cy, r; //circle
  16.  
  17. System.out.print("Enter cx: ");
  18. cx = in.nextDouble();
  19. System.out.print("Enter cy: ");
  20. cy = in.nextDouble();
  21. System.out.print("Enter r: ");
  22. r = in.nextDouble();
  23. System.out.print("Enter p1x: ");
  24. p1x = in.nextDouble();
  25. System.out.print("Enter p1y: ");
  26. p1y = in.nextDouble();
  27. System.out.print("Enter p2x: ");
  28. p2x = in.nextDouble();
  29. System.out.print("Enter p2y: ");
  30. p2y = in.nextDouble();
  31.  
  32. if(p2x == p1x){
  33. //line is vertical, or both points are in the same position.
  34. double dx = p2x - cx;
  35. if(dx*dx<r*r){
  36. //infinite line hits circle check y values.
  37.  
  38. } else{
  39. System.out.println("doesn't touch.");
  40. }
  41. } else{
  42.  
  43. double m = (p2y - p1y)/(p2x - p1x);
  44.  
  45. double b = p1y - m*p1x;
  46.  
  47. double B = (b - m*cx-cy);
  48. if((r*r*(m*m+1))>B*B){
  49. //inifinite line hits the circle. Now to solve the actual x positions.
  50. double radical = Math.sqrt((m*m+1)*r*r - B*B);
  51. double x0 = cx + (-m*B + radical)/(m*m+1);
  52. double x1 = cx + (-m*B - radical)/(m*m+1);
  53. System.out.println("infinite line touches at: " + x0 + ", and " + x1);
  54. //finaly check if either x0 or x1 are between p1x and p2x.
  55. if((x0>p1x&&x0<p2x)||(x0>p2x&&x0<p1x)||(x1>p1x&&x1<p2x)||(x1>p2x&&x1<p1x)){
  56. System.out.println("line segment touches");
  57. }
  58. } else{
  59. System.out.println("doesn't touch");
  60. }
  61. }
  62. }
  63. }
Success #stdin #stdout 0.06s 711680KB
stdin
1.0 1.0 3.0 0.0 0.0 8.0 10.0
stdout
Enter cx: Enter cy: Enter r: Enter p1x: Enter p1y: Enter p2x: Enter p2y: infinite line touches at: 3.75322563399777, and 0.4418963172217425
line segment touches