This program will keep track of the total distance tor a trip through several ci
ID: 3688131 • Letter: T
Question
This program will keep track of the total distance tor a trip through several cities Assume that we have cities 0,1, 2, and 3. We will enter the number for each city on the route as the program asks for each city from start to finish. Assume that the distance are as follows: Notice that only the distances for the bottom triangle of the table are shown. The assumption is that the distance between 2 cities does not depend on which direction you are going. So: the program should use a ragged array, as described on page 290 of the textbook. The program should perform as follows. The program will ask for the starting point of the trip. It will accept a number as the start of this step in the travel. It will begin a loop which will: ask for the next stop in the trip store the user s reply as the number for the stopping point copy the values of the starting and ending points into the values of variables r and c such that the value of r is greater than or equal to the value of c use the values of r and c (for row and column values) to find the next distance traveled and add it to the total distance copy the value of the stopping point into the variable for the starting point o ask if there is another city to visit get the reply from the user and if it is Y or y back to the top of the loop display the value of the total distance traveledExplanation / Answer
package chegg;
import java.util.Scanner;
public class TotalDistance {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int distances[][] = new int[4][];
for (int i = 0; i < 4; i++) {
distances[i] = new int[i+1];
}
distances[0][0] = 0;
distances[1][0] = 10;
distances[1][1] = 0;
distances[2][0] = 20;
distances[2][1] = 30;
distances[2][2] = 0;
distances[3][0] = 40;
distances[3][1] = 50;
distances[3][2] = 60;
distances[3][3] = 0;
System.out.println("Enter starting point of trip");
int start = scanner.nextInt();
int r, c, stop, totalDistanceTravelled = 0;
while (true) {
System.out.println("Enter next stop in trip");
stop = scanner.nextInt();
r = start > stop ? start : stop;
c = start + stop - r;
totalDistanceTravelled += distances[r][c];
start = stop;
System.out.println("Is there another city to visit?");
String input = scanner.next();
if (input != "y" && input != "Y")
break;
}
System.out.println("Total distance totravalled = " + totalDistanceTravelled);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.