【问题标题】:Java: Error with reading in file with delimiterJava:使用分隔符读取文件时出错
【发布时间】:2013-04-17 12:22:47
【问题描述】:

我有一个包含多个字段的文件,我需要将它们单独存储到一个数组中。

Steve;stiffy;123;88
Sam;sammy;456;55

但是当我尝试存储它们时,我不断收到错误提示 java.util.NoSuchElementException

这是我存储数据的代码

void loadCustomer(){

    try {
        Scanner sc = new Scanner(new File("CustomerInfo.txt"));
        sc.useDelimiter(";");
        while (sc.hasNext())
        {
            cusName.add(sc.next());
            cusUser.add(sc.next());
            cusPass.add(sc.next());
            cusCCNum.add(sc.next());
        }
}

我可以通过改变来让它工作

cusCCNum.add(sc.next());

到

cusCCNum.add(sc.nextLine());

但它会忽略分隔符,当我打印出 cusCCNum.get(1) 时,它会显示

;88

而不是

88

我哪里做错了?

【问题讨论】:

  • 你能提供你的错误的行号和堆栈跟踪吗?它可能会让我们了解问题所在。
  • 将分隔符更改为sc.useDelimiter("[;\\n]");。
  • 在这个问题上接受的答案看起来很有帮助:stackoverflow.com/questions/3493230/scanner-usedelimiter
  • 感谢大家的投入,使用 sc.useDelimiter("[;\\n]"); 和 scanner.useDelimiter(";|\n"); 解决了我的问题

标签: java arrays delimiter


【解决方案1】:

88 和 Sam.. 之间没有分隔符。

  scanner.useDelimiter(";|\n");

【讨论】:

    【解决方案2】:

    使用字符串标记器而不是分隔符。 以字符串形式获取输入并通过 ; 解析它字符作为令牌。

    学习,如何使用 stringtokenizer here

    【讨论】:

      【解决方案3】:

      当您为每个元素调用 4 个下一个元素检查是否有 1 个下一个元素时,您会导致异常,这将执行以下操作:

      while (RecentElement is not the last one)
      {
          Read (RecentElement + 1)
          Read (RecentElement + 2)
          Read (RecentElement + 3)
          Read (RecentElement + 4)
      }
      

      当你得到exception of the next() method 时,因为你访问了一个不存在的元素:

      抛出:NoSuchElementException - 如果没有更多令牌可用

      您应该使用新行作为分隔符,并为每个新行解析记录中的数据,例如使用 split 函数:

         sc.useDelimiter("\n");      
         while (sc.hasNext())
         {
             for(String g: sc.next().split(";"))
               System.out.println(g);          
         }
      

      【讨论】:

        【解决方案4】:

        看起来您需要读取每一行,使用分隔符标记它并将值设置为数组。

        我可以通过 StringTokenizer 来做到这一点。

        while (sc.hasNextLine())            {               
                        StringTokenizer st =  new StringTokenizer(sc.nextLine(),";");               
                        while (st.hasMoreElements()) {
                            System.out.println(st.nextElement());
                        }
                    }
        

        我很惊讶,需要阅读更多关于 Scanner api 的内容,看看为什么它不能与扫描仪一起使用。

        【讨论】:

          猜你喜欢
          • 2012-12-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-31
          • 2016-05-31
          • 2019-12-07
          • 1970-01-01
          相关资源
          最近更新 更多