In: Computer Science
What is the perimeter of the shape made from the file datatest4.txt whose contents are shown below (just give to two decimal (places)? JAVA!
-3, 9
-8, 7
-12, 4
-6, -2
-4, -6
2, -8
6, -5
10, -3
8, 5
4, 8
OUTPUT ::
RAW CODE ::
_____________________________________________ main.java ________________________________________
import java.util.*;
import java.io.*;
class Main{
public static double distance(int[] A, int[] B){
int x,y;
x = A[0] - B[0] ; y = A[1] - B[1];
// X wise distance , Y wise distance
return Math.sqrt((x*x)+(y*y)); //
Pythagerous theorem
}
public static void main(String[] args){
String line; String[] val; //
Declarng variables
int[] start = new int[2];
int[] temp = new int[2];
int[] cur = new int[2];
start[0] = -1 ; start[1] =
-1;
int perimeter = 0; // perimeter
stars with 0
try{
File fl = new
File("datatest4.txt");
Scanner sc = new
Scanner(fl);
while
(sc.hasNextLine()){
line = sc.nextLine(); val = line.split(", "); //
Read line by line, split the values
cur[0] = Integer.parseInt(val[0]); // Converting
Them to integers
cur[1] = Integer.parseInt(val[1]);
if(start[0] == -1 && start[1] == -1){ //
if it start line
start[0] = cur[0]; start[1] =
cur[1]; // Record it in start
temp[0] = cur[0]; temp[1] =
cur[1]; // Storing past values in temp
continue; // For first one
continue
}
perimeter += distance(temp, cur); // Calculate
distance for current to past value
temp[0] = cur[0]; temp[1] = cur[1]; // Storing
past values in temp
}
perimeter +=
distance(cur, start); // Finally Calculate distance for end to
start
System.out.println("Perimeter is : "+perimeter); // Printing
} catch(Exception e){
System.out.println("Error");
}
}
}
__________________________________________________________________________________________________