0
I’m trying to make this code, which is basically a six-by-six two-dimensional array with the distance between six cities, then collect the route that the user did in a simple array [6], and calculate the total number of kilometers he traveled.
The code:
package rotas;
import java.util.*;
public class Rotas {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[][] km = {{0, 20, 32, 45, 85, 90}, {20, 0, 20, 40, 65, 70}, {32, 20, 0, 25, 48, 49},
{45, 40, 25, 0, 39, 52}, {85, 65, 48, 39, 0, 36}, {90, 70, 49, 52, 36, 0}};
int[] rota = new int[6];
String[] rota_r = new String[6];
String[] cid = {"Belo Horizonte", "Contagem", "Betim", "Juatuba", "Pará de Minas", "Itaúna"};
int km_rodados = 0;
for(int i = 0; i < 6; i++){
for(int j = 0; j < 6; j++){
System.out.printf("%d\t", km[i][j]);
}
System.out.printf("\n");
}
System.out.println("Digite sua rota: \n\n1. Belo Horizonte\t2. Contagem\t3. Betim\n"
+ "4. Juatuba\t5. Pará de Minas\t 6.Itaúna\n");
for(int i = 0; i < 6; i++){
rota[i] = input.nextInt();
}
System.out.println("\nROTA: \n");
for(int i = 0; i < 6; i++){
System.out.printf("%d. %s\n", i+1, cid[rota[i]-1]);
}
for(int i = 0; i <= 6; i++){
km_rodados = km_rodados + km[rota[i]][rota[i+1]];
}
System.out.printf("\nKilômetros rodados: %d\n", km_rodados);
}
}
Until the part to collect the route and display them in order beauty, but at the time to calculate the km, the for for in 5. It gives a help ai, I could not think of another way to calculate this.
How does the 6x6 km array with the ditties between cities work? Betim is the city "3" and Itaúna is the City "6", therefore the distance between Betim and Itaúna is in 'km[2][5]' ("3-1=2" and "6-1=5")?
– Douglas
It would be more or less, the user filled the array with (5, 3, 1, 2, 3, 4), so it will be the distance from the city "5" and the city "3", city "3" to the city "1", and so on, that is, in the array km[4][2] (because it will start from 0)the distance between Pará de Minas and Betim is 48.
– thatsadkatyperrymeme
replace the latter for: "for(int i = 0; i <= 6; i++)" by "for(int i = 0; i < 4; i++)" solves the problem?
– Douglas
keeps giving error :/
– thatsadkatyperrymeme
I think your code is an exercise, but if it’s not, I suggest refactoring it, because its logic is very obscure, besides, it’s very inflexible (for example, if you want to work with 7 cities instead of 6, you’ll have to change a lot in this code).
– Douglas