How can I do this, calculateDistance method: Receives a route (which is an array
ID: 3539032 • Letter: H
Question
How can I do this,
calculateDistance method: Receives a route (which is an array), for each route segment (pair of cities), has to
display cities names and the distance between those two cities and the total-distance until that segment. If doesn%u2019t
exist a distance for any pair, the program will display the segment but the total-distance is not affected but must
continue calculating.
Like this
Output
-------------------------------------------------------------------
Distance for route :
From : kalamazoo To grandRapids : 51 Accum: 51
From : grandRapids To lansing : 66 Accum: 117
From : lansing To kalamazoo : -1 Accum: 117 <------no distance yet
This it the code I currently have but it only shows accumalitve distance and doest not say, no distance yet, for the incorrect ones
public void calculateDistance(String[] route){
System.out.println("Distance for route :");
int Accum = 0;
for(int i=0; i<route.length-1; i++){
if(distances[findIndexCity(route[i])][findIndexCity(route[i+1])]>0)
Accum = Accum + distances[findIndexCity(route[i])][findIndexCity(route[i+1])];
System.out.println("From : " + route[i] + " To " + route[i+1] + " : " + " Accum: " + Accum);
}
}
Mine looks like this
------------------------------
Distance for route :
From : kalamazoo To grandRapids : Accum: 51
From : grandRapids To lansing : Accum: 117
From : lansing To kalamazoo : Accum: 117
Explanation / Answer
//CORRECTED CODE
public void calculateDistance(String[] route){
System.out.println("Distance for route :");
int Accum = 0;
int d=0;
for(int i=0; i<route.length-1; i++){
d=distances[findIndexCity(route[i])][findIndexCity(route[i+1])];
if(d>0)
{
Accum = Accum + d;
System.out.println("From : " + route[i] + " To " + route[i+1] + " : " + d + " Accum: " + Accum);
}
else
{
System.out.println("From : " + route[i] + " To " + route[i+1] + " : " + d + " Accum: " + Accum + " <------no distance yet");
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.