Write a Java application that finds the closest state to a given latitude and lo
ID: 3596746 • Letter: W
Question
Write a Java application that finds the closest state to a given latitude and longitude. The file states.txt contains the approximate latitude (North) and longitude (West) of the center of each state. Your program should ask the user for a latitude and longitude. It should then search the file for the state that is closest to the given location. The distance can be calculated by
-Write in java language
states.txt:
Write a Java application that finds the closest state to a given latitude and longitude. The file states.txt contains the approximate latitude (North) and longitude (West) of the center of each state. Your program should ask the user for a latitude and longitude. It should then search the file for the state that is closest to the given location. The distance can be calculated by distance= VlatitudeDifference? + longitude Difference? Each line in the states.txt file contains atitude longitude . name of the state Example input and output Enter your X and Y location >36 79.75 North Carolina is the closest state Enter your X and Y location >38 90 Missouri is the closest stateExplanation / Answer
import java.util.Scanner; import java.io.*; public class NearState{ public static void main(String a[]){ System.out.print("Enter your X and Y location >"); Scanner sc = new Scanner(System.in); double latitude = sc.nextDouble(); double longitude = sc.nextDouble(); BufferedReader br = null; FileReader fr = null; String resultState = ""; double minDistance = 100000; try { fr = new FileReader("states.txt"); br = new BufferedReader(fr); String line; int i=0; while ((line = br.readLine()) != null) { String details[] = line.split(" "); double latitude2 = Double.parseDouble(details[0]); double longitude2 = Double.parseDouble(details[1]); double distance = distance(latitude, longitude, latitude2, longitude2); if(minDistance > distance){ minDistance = distance; resultState = details[2]; } } } catch (IOException e) { e.printStackTrace(); } System.out.println(resultState + " is the closest state"); } public static double distance(double latitude1, double longitude1,double latitude2, double longitude2){ double latitudeDiff = latitude1 - latitude2; double longitudeDiff = longitude1 - longitude2; return Math.sqrt((latitudeDiff*latitudeDiff) + (longitudeDiff*longitudeDiff)); } }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.