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?
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
.
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.
Also make sure prices
and XY
are accessible from calculateFees
. XY
should also be a String[]
, not a String
.
Get the index of the X
from XY
, say i
.
Get the index of Y
from XY
, say j
.
Get the fare using, prices[i][j]
.
You might need to loop over the array XY testing for the given string each twice. You can save time by using a HashMap from String to Integer index instead.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.