【问题标题】:How to use delimiter to find the end of the line? [duplicate]如何使用分隔符找到行尾? [复制]
【发布时间】:2015-04-20 04:29:19
【问题描述】:

我正在尝试阅读此模式...Scanner.useDelimiter 是什么?

这个输入是:

489 490-1; 491-1; 492-1; 493-1; 494-1; 495-1; 496-1; 497-1; 498-1; 499-1; 500-1;
490 491-1; 492-1; 493-1; 494-1; 495-1; 496-1; 497-1; 498-1; 499-1; 500-1;
491 492-1; 493-1; 494-1; 495-1; 496-1; 497-1; 498-1; 499-1; 500-1;
492 493-1; 494-1; 495-1; 496-1; 497-1; 498-1; 499-1; 500-1;
493 494-1; 495-1; 496-1; 497-1; 498-1; 499-1; 500-1;
494 495-1; 496-1; 497-1; 498-1; 499-1; 500-1;
495 496-1; 497-1; 498-1; 499-1; 500-1;
496 497-1; 498-1; 499-1; 500-1;
497 498-1; 499-1; 500-1;

我需要将 489, 490, 491 放入一个控件数组中,并将 490 ,1 ,491, 1(第二列和它们)放入一个集合中。

我试过这个分隔符,但没有用:
Scanner(readerFile).useDelimiter("[^0-9]+");

因为他在我的while(readerFile.hasNextInt()) 中保持循环并且不调用nextLine() 函数,读取集合中的所有输入。

while (readerFile.hasNextLine()){
   readerFile.nextLine();
   vector[i] = readerFile.nextInt();
   while (readerFile.hasNextInt()){
       linkedList.add(reader.nextInt());
   }
}

如何控制下一行?

【问题讨论】:

  • 一旦从标题中删除标签,就真的没有标题了。 Should Questions include tags in the title?
  • useDelimiter 不会影响nextLine 的行为,afaik。当您调用 nextLine 时,将消耗整行(在您的情况下,由于您没有将其分配给变量,因此将其丢弃)
  • 是的,是的,但我想读取所有输入变量(489),集合(490 1 491 1 492 1 493 1 494 1 495 1 496 1 497 1 498 1 499 1 500 1)之后我需要转到下一行。如果我无法控制并且不调用下一行,他会继续阅读集合中的下一个 int,明白吗?
  • 这是一个不同的问题。

标签: java regex java.util.scanner delimiter


【解决方案1】:

我可能会这样做:

伪代码:

While has next line
    s = next line
    split = s.split(" ", 2);
    vector[i] = split[0]; // or whatever you want to do with the first value
    values = split[1].split(";")
    foreach value in values
        linkedList.add(value); // or whatever you want to do with the rest of the values

【讨论】:

  • 我这里没有,在 ; 之后有空格,第一次拆分不会出错?
  • @NicolasBontempo 第一次拆分是使用split(" ", 2) 完成的,它将部分的数量限制为两个,即仅在第一个空格上拆分
  • 好的,无论如何,谢谢,如果工作我会尝试回来回复(:
猜你喜欢
  • 2019-09-08
  • 2017-03-11
  • 1970-01-01
  • 1970-01-01
  • 2017-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-14
相关资源
最近更新 更多