好的,所以我刚开始在大学里学习java,而这个代码让我烦恼。基本上,我的教授要求我们写这将有将存储六个城市之间的距离,两dementional阵列中的代码,它是这样的:我只是不能让这个java代码工作
然后,我们就必须收集信息关于简单数组中用户的路由,例如。 1 5 4 3 2 1.
并且根据用户通知的数字,我们将必须计算他驾驶的总距离。
这是我写的:
package routes;
import java.util.*;
public class Routes {
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[] routes = new int[6];
String[] route_r = new String[6];
String[] city = {"Belo Horizonte", "Contagem", "Betim", "Juatuba", "Pará de Minas", "Itaúna"};
int km_distance = 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("Enter your route: \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("\nRoute: \n");
for(int i = 0; i < 6; i++){
System.out.printf("%d. %s\n", i+1, city[route[i]-1]);
}
for(int i = 0; i < 6; i++){
km_distance = km_distance + km[route[i]][route[i+1]];
}
System.out.printf("\nTotal KM: %d\n", km_distance);
}
}
但不知什么原因,这是行不通的。我调试它,我意识到最后的结构只循环四次,然后崩溃。请发送帮助。
编辑:输出误差
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at rotas.Rotas.main(Rotas.java:41)
C:\...\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
RUN FAILED (exit value 1, total time: 47ms)
请发帖输出错误 – MigSena
另外这个不能是实际的代码,这个不会编译 – UnholySheep
欢迎来到Stack Overflow!看起来你可能会问作业帮助。虽然我们本身没有任何问题,但请观察这些[应做和不应该](http://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions/338845#338845),并相应地编辑您的问题。 (即使这不是家庭作业,请考虑建议) –