簡體   English   中英

Java,如何從二維二維數組中找到特定值?

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

我需要計算兩個地點之間的價格,我有以下數據結構,它們保持區域之間的價格:

                  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不在數組中的情況留給讀者練習。

還要確保可以從calculateFees訪問pricesXY XY也應該是String[] ,而不是String

XY獲取X的索引,比如i

XY得到Y的索引,比如j

prices[i][j]使用票價。

您可能需要每次兩次遍歷給定字符串的數組XY測試。 您可以通過使用從String到Integer索引的HashMap來節省時間。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM