gpt4 book ai didi

java - Arraylist 将第一个元素生成为 null

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:23:23 24 4
gpt4 key购买 nike

我一直在尝试实现 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());
}
}

当我尝试执行代码时,以下是我得到的输出:

Enter the number of Cities 3

Enter the details for city 0:

Name of the vertex: a

Please enter the details for city 1:

Name of the vertex: b

Please enter the details for city 2:

Name of the vertex: c

Entry for i =0 is:

Entry for i =1 is: a

Entry for i =2 is: b

谁能解释一下我哪里出错了?

注意:Vertex 是另一个类,它只包含顶点的必要细节,如名称和边数组。

最佳答案

添加scannerObj.nextLine();

之后

int no_Of_Cities = scannerObj.nextInt();

这将消耗包含您刚刚读取的 int 的行的末尾,并防止在您首次调用 String name = new String(scannerObj.nextLine( ));

关于java - Arraylist 将第一个元素生成为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26586114/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com