Advertisement
Ligh7_of_H3av3n

03. Longer Line

Feb 2nd, 2024
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.35 KB | None | 0 0
  1. package MoreExercise;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class LongerLine {
  6.     public static void main(String[] args) {
  7.         Scanner scanner = new Scanner(System.in);
  8.  
  9.         // Read coordinates of four points
  10.         int x1 = scanner.nextInt();
  11.         int y1 = scanner.nextInt();
  12.         int x2 = scanner.nextInt();
  13.         int y2 = scanner.nextInt();
  14.         int x3 = scanner.nextInt();
  15.         int y3 = scanner.nextInt();
  16.         int x4 = scanner.nextInt();
  17.         int y4 = scanner.nextInt();
  18.  
  19.         // Calculate lengths of both lines
  20.         double length1 = calculateLength(x1, y1, x2, y2);
  21.         double length2 = calculateLength(x3, y3, x4, y4);
  22.  
  23.         // Determine the point closer to the center for each line
  24.         boolean firstLineFirstPointClosest = isCloserToCenter(x1, y1, x2, y2);
  25.         boolean secondLineFirstPointClosest = isCloserToCenter(x3, y3, x4, y4);
  26.  
  27.         // Determine which line is longer
  28.         if (length1 > length2) {
  29.             // Print the longer line starting from the point closer to the center
  30.             if (firstLineFirstPointClosest)
  31.                 printLine(x1, y1, x2, y2);
  32.             else
  33.                 printLine(x2, y2, x1, y1);
  34.         } else if (length2 > length1) {
  35.             // Print the longer line starting from the point closer to the center
  36.             if (secondLineFirstPointClosest)
  37.                 printLine(x3, y3, x4, y4);
  38.             else
  39.                 printLine(x4, y4, x3, y3);
  40.         } else {
  41.             // Lines are of equal length, print only the first one
  42.             printLine(x1, y1, x2, y2);
  43.         }
  44.     }
  45.  
  46.     // Method to calculate the length of a line given two points
  47.     private static double calculateLength(int x1, int y1, int x2, int y2) {
  48.         return Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2));
  49.     }
  50.  
  51.     // Method to check which point is closer to the center
  52.     private static boolean isCloserToCenter(int x1, int y1, int x2, int y2) {
  53.         double distance1 = Math.sqrt(Math.pow(x1, 2) + Math.pow(y1, 2));
  54.         double distance2 = Math.sqrt(Math.pow(x2, 2) + Math.pow(y2, 2));
  55.         return distance1 <= distance2;
  56.     }
  57.  
  58.     // Method to print a line in the required format
  59.     private static void printLine(int x1, int y1, int x2, int y2) {
  60.         System.out.printf("(%d, %d)(%d, %d)\n", x1, y1, x2, y2);
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement