Page 1 of 1

6. A program that prompts the user for five coordinates and calculates the longest distance between them is shown below.

Posted: Mon May 02, 2022 12:25 pm
by answerhappygod
6. A program that prompts the user for five coordinates and
calculates the longest
distance between them is shown below.
import java.util.Scanner;
public class LongestDistance {
private static final int NUM_COORDS = 5;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] xs = new int[NUM_COORDS];
int[] ys = new int[NUM_COORDS];
for (int i = 0; i < NUM_COORDS; i++) {
System.out.println("Enter x value:");
xs = scanner.nextInt();
System.out.println("Enter y value:");
ys = scanner.nextInt();
}
double longestDistance = 0.0;
for (int i = 0; i < NUM_COORDS; i++) {
for (int j = 0; j < NUM_COORDS; j++) {
int xdiff = xs - xs[j];
int ydiff = ys - ys[j];
double distance
= Math.sqrt(xdiff*xdiff + ydiff*ydiff);
longestDistance
= Math.max(distance, longestDistance);
}
}
System.out.println("The longest distance is " +
longestDistance);
}
}
(a) Name and briefly describe a class that could be created to
better organise
the data manipulated by this program. Your answer should
include
• the name of the class, and
• the names and types of its instance variables. [3 marks]
(b) The readability of this code could be improved by splitting
it up into separate
methods. Name and briefly describe at least two methods that
could be
introduced. For each method, your answer should include
• the name of the method,
• the names and types of each argument, and
• the return type of the method.