我正在尝试使用定界符提取文档中的第一个数字,该文档有 31 行,类似于“105878-798##176000##JDOE”,并将其放入一个 int 数组中。 我感兴趣的数字是“105878798”,数字个数不一致。
我写了这篇文章,但无法弄清楚当我到达(该行的)第一个定界符时如何更改该行。
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args) throws Exception {
int n = 0;
String rad;
File fil = new File("accounts.txt");
int[] accountNr = new int[31];
Scanner sc = new Scanner(fil).useDelimiter("##");
while (sc.hasNextLine()) {
rad = sc.nextLine();
rad.replaceAll("-","");
accountNr[n] = Integer.parseInt(rad);
System.out.println(accountNr[n]);
n++;
System.out.println(rad);
}
}
}
最佳答案
不要为此使用扫描器,使用 StringTokenizer 并将定界符设置为##,然后继续调用 .nextElement(),无论多长,您都会得到下一个数字。
StringTokenizer st2 = new StringTokenizer(str, "##");
while (st2.hasMoreElements()) {
log.info(st2.nextElement());
}
(当然,你可以用不同的方式迭代..)
关于java - 使用定界符,读到第一个定界符,然后换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14507960/