有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

方法Java,如何从二维双精度数组中找到特定值?

我需要计算两个地点之间的价格,我有以下数据结构,用于保存区域之间的价格:

                  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;
}

共 (2) 个答案

  1. # 1 楼答案

    XY获取X的索引,比如i

    XY中获取Y的索引,比如j

    使用,prices[i][j]获取车费

    您可能需要对给定字符串的数组XY进行两次循环测试。通过使用从字符串到整数索引的哈希映射,可以节省时间

  2. # 2 楼答案

    你需要弄清楚哪些数组索引适用

    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不在数组中的情况下处理这个问题留给读者作为练习

    还要确保pricesXY可以从calculateFees访问XY也应该是String[],而不是String