【发布时间】:2014-10-27 11:02:57
【问题描述】:
我一直在尝试实现 Dijkstra 算法。以下是读取输入的代码:
System.out.println("Enter the number of Cities ");
int no_Of_Cities = scannerObj.nextInt();
List<Vertex> Vertices = new ArrayList<Vertex>(no_Of_Cities) ;
for (int itr = 0; itr < no_Of_Cities; itr++){
System.out.println("Enter the details for city "+itr+": ");
System.out.println("Name of the vertex: ");
String name = new String(scannerObj.nextLine());
Vertex vertexObj = new Vertex(name);
Vertices.add(vertexObj);
}
display(Vertices);
显示功能如下:
public static void display(List<Vertex> vertices){
int length = vertices.size();
for(int i =0;i<length;i++){
System.out.println();
System.out.println("Entry for i ="+i+" is: "+vertices.get(i).getName());
}
}
当我尝试执行代码时,我得到以下输出:
输入城市数量 3
输入城市 0 的详细信息:
顶点名称: 一个
请输入城市 1 的详细信息:
顶点名称: b
请输入城市 2 的详细信息:
顶点名称: c
i =0 的条目是:
i =1 的条目是:a
i =2 的条目是:b
谁能解释我在哪里犯了错误?
注意:Vertex 是另一个类,它只包含顶点的必要细节,如名称和边数组。
【问题讨论】:
-
请注意:我建议使用
Integer.parseInt(scannerObj.nextLine())而不是scannerObj.nextInt() -
@OlaviMustanoja - 你的方式将比他当前的版本更有效。 :)
-
感谢您的建议,我已将您的方式纳入我的程序。 :) @TheLostMind
-
@Arpit_Spartan - 欢迎您。 :)