我需要计算两个位置之间的价格,我具有以下数据结构来保存区域之间的价格:

                  Washington  Niagra Falls  New York
Washington        0,          6.30,         8.30
Niagra Falls      5.30,       0   ,         5.30
New York          3.20,       4.30,         0


如何创建一种基于字符串X和字符串Y位置在二维数组中查找值的方法?

这是我到目前为止的代码:

String Location X = "Washington";
String Location Y = "New York";

String XY = {"Washington", "Niagara Falls", "New York"};
//Cost of the trips
double[][] prices = {
    {0,    6.30, 8.30},
    {5.30, 0,    5.30},
    {3.20, 4.30, 0   },
};


在上述情况下,华盛顿->纽约应为8.30

方法应该是这样的:

public double calculateFees(String X, String Y){
    //add code here.

    double fares;
 return fares;
}

最佳答案

您需要确定将应用哪些数组索引。

public double calculateFees(String X, String Y){
    int xArrIdx=0;
    for(xArrIdx=0; xArrIdx<XY.length; xArrIdx++){
        if(XY[xArrIdx].equals(X)) break;

    }
    for(yArrIdx=0; yArrIdx<XY.length; yArrIdx++){
        if(XY[yArrIdx].equals(Y)) break;

    }

    return prices[xArrIdx][yArrIdx];
}


读者可以练习一下在数组中没有XY的情况。

还要确保可以从prices访问XYcalculateFeesXY也应该是String[],而不是String

09-30 13:56
查看更多