Java 将第一个元素生成为null的Arraylist
我一直在尝试实现Dijkstra算法。以下是读取输入的代码:Java 将第一个元素生成为null的Arraylist,java,algorithm,arraylist,Java,Algorithm,Arraylist,我一直在尝试实现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 (
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);
System.out.println(“输入城市数量”);
int no_Of_Cities=scannerObj.nextInt();
列表顶点=新阵列列表(没有城市);
对于(int itr=0;itr<0个城市的数量;itr++){
System.out.println(“输入城市的详细信息”+itr+“:”);
System.out.println(“顶点的名称:”);
字符串名称=新字符串(scannerObj.nextLine());
顶点vertexObj=新顶点(名称);
顶点。添加(vertexObj);
}
显示(顶点);
显示功能如下:
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());
}
}
公共静态空白显示(列出顶点){
int length=顶点.size();
对于(int i=0;iAddscannerObj.nextLine();
之后
int-no-Of-Cities=scannerObj.nextInt();
这将消耗包含您刚才读取的int的行的结尾,并防止在您第一次调用String name=new String(scannerObj.nextLine());
添加scannerObj.nextLine();
之后
int-no-Of-Cities=scannerObj.nextInt();
这将消耗包含您刚才读取的int的行的结尾,并防止在您第一次调用String name=new String(scannerObj.nextLine());
String name=new String(scannerObj.nextLine());
此行导致问题,因为它导致输入跳到下一行,从而跳过城市0的输入
使用此代码它将工作-:
字符串名称=新字符串(scannerObj.next());字符串名称=新字符串(scannerObj.nextLine());
此行导致问题,因为它导致输入跳到下一行,从而跳过城市0的输入
使用此代码它将工作-:
String name=new String(scannerObj.next());只是一个小提示:我建议使用Integer.parseInt(scannerObj.nextLine())
而不是scannerObj.nextInt()
@olavimutanoja-你的方法将比他当前的版本更有效。:)感谢您的建议,我已将您的方式纳入我的计划中。:)@TheLostMind@Arpit_Spartan-不客气。:)请注意:我建议使用Integer.parseInt(scannerObj.nextLine())
而不是scannerObj.nextLine()
@olavimutanoja-您的方式将比他当前的版本更有效。:)感谢您的建议,我已将您的方式纳入我的程序中。:)@TheLostMind@Arpit_Spartan-不客气。:)我按照你的建议做了,但不起作用。同样的问题存在。第一个元素仍然为空。我按照你的建议做了,但不起作用e同样的问题存在,第一个元素仍然为空谢谢@Puneet您建议的修复工作正常,但问题是输入被移动了一个索引位置。实际上,最后一个值丢失了。您能解释一下为什么会发生这种情况吗?谢谢@Puneet您建议的修复工作正常但问题是输入被移动了一个索引位置。实际上,最后一个值丢失了。你能解释一下为什么会发生这种情况吗?