简体   繁体   English

Java,如何从二维二维数组中找到特定值?

[英]Java, How to find specific value from two dimensional array of doubles?

I need to calculate the price between two locations, I have the following data structure which holds the price between areas: 我需要计算两个地点之间的价格,我有以下数据结构,它们保持区域之间的价格:

                  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

How do I create a method that it will find the value in the two dimensional array based on the String X and String Y Locations? 如何创建一个方法,它将根据字符串X和字符串Y位置在二维数组中找到值?

Here is the code I have so far: 这是我到目前为止的代码:

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

In the above case Washington -> New York should be 8.30 . 在上述情况下,华盛顿 - >纽约应该是8.30

Method should be something like this: 方法应该是这样的:

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

    double fares;
 return fares;
}

You'd need to figure out which array indices would apply. 您需要确定应用哪些数组索引。

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

Making this handle cases where X or Y aren't in the array is left as an exercise to the reader. 使这个处理XY不在数组中的情况留给读者练习。

Also make sure prices and XY are accessible from calculateFees . 还要确保可以从calculateFees访问pricesXY XY should also be a String[] , not a String . XY也应该是String[] ,而不是String

Get the index of the X from XY , say i . XY获取X的索引,比如i

Get the index of Y from XY , say j . XY得到Y的索引,比如j

Get the fare using, prices[i][j] . prices[i][j]使用票价。

You might need to loop over the array XY testing for the given string each twice. 您可能需要每次两次遍历给定字符串的数组XY测试。 You can save time by using a HashMap from String to Integer index instead. 您可以通过使用从String到Integer索引的HashMap来节省时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM