我是Java的新手,正在尝试获取stations字段中变量之间的距离,但这似乎不起作用。

public static void main(String[]args){
double[] stations = {10,20,30};{
for(int i=0;i<stations.length-2;i++){
    double distance=stations[i+1] + stations[i];
}

最佳答案

您需要substract而不是add来计算彼此之间的距离。因此,您需要两个for循环才能获得所有组合。

例:

public static void main(String args[]){

            int i =0;
            int j=0;
            double[] stations = {10,20,30};
            for(i=0;i<stations.length;i++){
                for(j=i+1;j<stations.length;j++){
                 System.out.println("distance between station "+i+" and station "+j+" is "+ (stations[j] - stations[i]));
                }
            }
}


输出:

distance between station 0 and station 1 is 10.0
distance between station 0 and station 2 is 20.0
distance between station 1 and station 2 is 10.0

10-06 12:37