【问题标题】:Arraylist generating first element as nullArraylist 将第一个元素生成为 null
【发布时间】: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 - 欢迎您。 :)

标签: java algorithm arraylist


【解决方案1】:

添加scannerObj.nextLine();

之后

int no_Of_Cities = scannerObj.nextInt();

这将消耗包含您刚刚读取的 int 的行的末尾,并防止在您第一次调用 String name = new String(scannerObj.nextLine()); 时将该(空)行用作下一个输入

【讨论】:

  • 我按照你的建议做了,但没有奏效同样的问题存在第一个元素仍然为空
【解决方案2】:

字符串名称 = new String(scannerObj.nextLine());

此行导致问题,因为它导致输入跳到下一行,从而跳过城市 0 的输入。

使用此代码它将起作用-: 字符串名称 = new String(scannerObj.next());

【讨论】:

  • 感谢@Puneet,您建议的修复工作正常,但问题是输入被移动了一个索引位置。实际上,最后一个值正在丢失。你能解释一下为什么会这样吗?
猜你喜欢
  • 1970-01-01
  • 2017-12-27
  • 2022-06-15
  • 1970-01-01
  • 2012-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-20
相关资源
最近更新 更多