我正在尝试编写一个地图导航应用程序。它应该将txt数据文件作为输入并将它们转换为列表并相应地显示它们。我面临的问题是我创建了一个名为Distance的基类和一个扩展了Distance的子类,称为位置。在距离类中有一个点的变量(我做的另一个类),它记录了位置本身的坐标。距离还有一种方法,用于计算当前位置与参数中传递给它的点之间的距离。现在问题是,在创建了多个类位置实例之后,类距离在点变量中只记录了一组值,就好像类距离只被实例化了一次。
我正在接受代码:
public class Distance {
private static Point point1;
private static Point point2;
Distance(Point coords){
point1=coords;
System.out.println("cons 1 long: "+point1.longitude);
System.out.println("cons 1 lat: "+point1.latitude);
}
public double calcDistance(Point coords2){
point2=coords2;
double theta;
System.out.println("point 1 long: "+point1.longitude);
System.out.println("point 2 long: "+point2.longitude);
if(Double.compare(point1.longitude,point2.longitude)>0){
theta = point1.longitude - point2.longitude;
System.out.println(point1.longitude+"-"+point2.longitude);
}else{
theta = point2.longitude - point1.longitude;
System.out.println(point2.longitude+"-"+point1.longitude);
}
System.out.println(theta);
double dist = Math.sin(deg2rad(point1.latitude))
* Math.sin(deg2rad(point2.latitude))
+ Math.cos(deg2rad(point1.latitude))
* Math.cos(deg2rad(point2.latitude))
* Math.cos(deg2rad(theta));
System.out.println(dist);
dist = Math.acos(dist);
System.out.println(dist);
dist = rad2deg(dist);
System.out.println(dist);
dist = dist * 60 * 1.1515;
System.out.println(dist);
dist = dist * 1.609344;
System.out.println(dist);
dist = (double) Math.round(dist * 100.0) / 100.0;
System.out.println(dist);
return dist;
}
private static double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
private static double rad2deg(double rad) {
return (rad * 180 / Math.PI);
}
}
顺便说一下,这个公式很好。这是位置类:
import java.util.List;
public class Location extends Distance{
public String name;
public Point coord;
public List<String> connections;
Location(String nam, Point coords, List<String> connect){
super(coords);
name=nam;
coord=coords;
connections=connect;
}
}
这就是正在读取txt文件并将其放入列表数组的地方。
public List<Location> processLocations(){
List<Location> locations= new ArrayList<Location>();
for (String location : locationData){
String[] data=location.split("____");
String name=data[0];
Point coord=new Point(Double.parseDouble(data[1]),Double.parseDouble(data[2]));
List<String> connections= new ArrayList<String>();
for(String connect: connectionsData){
String[] con=connect.split("____");
//System.out.println(con[0]+name);
if(con[0].equals(name)){
connections.add(con[1]);
}
}
Location loc=new Location(name,coord,connections);
locations.add(loc);
}//for location ends
return locations;
}//process location ends
如果我访问location.coords变量,它会给出给定位置的正确点。但如果我访问距离等级的point1,它会为所有位置提供相同的坐标。