我正在尝试使用定界符来提取具有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());
}
(当然,您可以用不同的方式进行迭代。)