Break a loop once the work is done.
[Persons_Comparator.git] / src / Country.java
1 import java.io.File;
2 import java.io.FileNotFoundException;
3 import java.util.List;
4 import java.util.Scanner;
5
6 public class Country {
7 private String name;
8 private String region;
9 private double lat;
10 private double lng;
11 private String flag;
12 private String csvFile = "data/countries.csv";
13
14 public Country() {
15 }
16
17 public Country(String name) {
18 setName(name);
19 initCountryFromCSV(name);
20 }
21
22 public Country(String name, String region, double lat, double lng, String flag) {
23 setName(name);
24 setRegion(region);
25 setLat(lat);
26 setLng(lng);
27 setFlag(flag);
28 }
29
30 public String getName() {
31 return name;
32 }
33
34 public void setName(String name) {
35 this.name = name;
36 }
37
38 public void setRegion(String region) {
39 this.region = region;
40 }
41
42 public double getLat() {
43 return lat;
44 }
45
46 public void setLat(double lat) {
47 this.lat = lat;
48 }
49
50 public double getLng() {
51 return lng;
52 }
53
54 public void setLng(double lng) {
55 this.lng = lng;
56 }
57
58 public String getFlag() {
59 return flag;
60 }
61
62 public void setFlag(String flag) {
63 this.flag = flag;
64 }
65
66 public int distanceTo(Country country) {
67 if ((this.getLat() == country.getLat()) && (this.getLng() == country.getLng())) {
68 return 0;
69 } else {
70 double theta = this.getLng() - country.getLng();
71 Double dist = Math.sin(Math.toRadians(this.getLat())) * Math.sin(Math.toRadians(country.getLat())) +
72 Math.cos(Math.toRadians(this.getLat())) * Math.cos(Math.toRadians(country.getLat())) *
73 Math.cos(Math.toRadians(theta));
74 dist = Math.acos(dist);
75 dist = Math.toDegrees(dist);
76 dist = dist * 60 * 1.1515;
77 // Kilometers
78 dist = dist * 1.609344;
79 return dist.intValue();
80 }
81 }
82
83 private void initCountryFromCSV(String name) {
84 Scanner scanner = null;
85 try {
86 scanner = new Scanner(new File(csvFile));
87 } catch (FileNotFoundException e) {
88 e.printStackTrace();
89 }
90 boolean found = false;
91 while (scanner.hasNext()) {
92 List<String> line = CSVUtils.parseLine(scanner.nextLine());
93 String countryList = line.get(0);
94 String[] countryArray = countryList.split(",");
95 String latLng = line.get(16);
96 String[] latLngArray = latLng.split(",");
97 if (countryArray[0].equals(name)) {
98 found = true;
99 setRegion(line.get(12));
100 setLat(Double.parseDouble(latLngArray[0]));
101 setLng(Double.parseDouble(latLngArray[1]));
102 setFlag(line.get(21));
103 break;
104 }
105 }
106 if (!found)
107 System.out.println("Country " + name + " not found");
108 scanner.close();
109 }
110
111 @Override
112 public String toString() {
113 return "Country{" +
114 "name='" + name + '\'' +
115 ", region='" + region + '\'' +
116 ", lat=" + lat +
117 ", lng=" + lng +
118 ", flag=" + flag +
119 '}';
120 }
121 }