【问题标题】:Read data from text file with scanner and multiple delimiters in JAVA在 JAVA 中使用扫描仪和多个分隔符从文本文件中读取数据
【发布时间】:2013-10-30 22:05:18
【问题描述】:

我有一个包含以下数据的文本文件:

20;
1: 39, 63;
2: 33, 7;
16: 33, 7;
3: 45, 27;
4: 8, 67;
5: 19, 47;
6: 15, 40;
...
20: 65, 54;

第一个整数是列表中条目的数量。

每一行都是一个条目。所以条目 1 的 x y 坐标分别为 39 和 63。 我知道我可以使用不同的分隔符来读取数据,但我不太确定如何实现这一点。目前我正在使用split()

以下代码读取每一行,但这显然不起作用,因为分隔符没有正确设置。有没有好办法让它发挥作用?

String[] temp = sc.next().split(";");
int productAmount = Integer.parseInt(temp[0]);
sc.nextLine();

for (int i = 0; i < productAmount; i++) {
    int productID = sc.nextInt();
    int x = sc.nextInt();
    int y = sc.nextInt();
    Product product = new Product(x, y, productID);
    productList.add(product);
}

【问题讨论】:

  • split 有一个 String 作为其参数。因此,您可以按照regex 语法使用多个分隔符。

标签: java regex parsing java.util.scanner


【解决方案1】:

在删除最后一个字符后,所有标记都可以转换为整数。您可以利用给定数据的这个属性。像这样定义一个方法:

int integerFromToken(String str) {
    return Integer.valueOf(str.substring(0, str.length() - 1));
}

返回令牌的整数部分(39, 返回3963; 返回63 等)。现在使用该方法从令牌中获取整数值(使用sc.next() 获得):

int productID = integerFromToken(sc.next());
int x = integerFromToken(sc.next());
int y = integerFromToken(sc.next());

【讨论】:

    【解决方案2】:

    如果你使用

    String[] temp = sc.next().split("[ ,:;]");
    

    那么您的temp 变量将只保存数字。字符串"[ ,:;]"regular expression,表示方括号中的任何字符都是分隔符。

    【讨论】:

      【解决方案3】:

      Croo说的很像,但是我用他的方法编译出错。

      为了避免通过包含空格作为分隔符来匹配空字符串,对我来说更有意义的是允许它们并使用对trim 的调用来摆脱它们。

      知道Scanner 可以被赋予regex 表达式作为分隔符,然后调用next 可以用来导航输入,这一点也很有用。

      sc.useDelimiter("[,:;]");
      int productAmount = Integer.parseInt(sc.next());
      int x, y, productID, i;
      for (i = 0; i < productAmount; i++) {
          productID = Integer.parseInt(sc.next().trim());
          x = Integer.parseInt(sc.next().trim());
          y = Integer.parseInt(sc.next().trim());
          productList.add(new Product(x,y,productID));
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多