有没有办法逐行将文件读入Java,每行都有一系列整数(每行不同数量的整数)。例如:
2 5
1 3 4 5
2 4 8
2 3 5 7 8
等等
我会将每行中的行号和数字读入一个二维数组。
现在,这是我的代码:
int i=1, j;
try{
Scanner sc=new Scanner(new File("mapinput.txt"));
while(sc.hasNext()){
String line=sc.nextLine();
while(line!=null){
j=sc.nextInt();
Adj[i][j]=1;
}
i++;
}
} catch(Exception e){System.err.println(e);};
我看到,这段代码的问题在于它在 String 行之后读取整数;我希望它读取那一行中的数字。有没有办法从字符串中读取数字?
更新:
我决定使用 StringTokenizer 路线;但是,当它到达我文件的最后一行时,我收到 java.util.NoSuchElementException: No line found 错误。这是我更新的代码:
try{
Scanner sc=new Scanner(new File("mapinput.txt"));
String line=sc.nextLine();
st=new StringTokenizer(line, " ");
do{
while(st.hasMoreTokens()){
j=Integer.parseInt(st.nextToken());
Adj[i][j]=1;
}
line=sc.nextLine();
st=new StringTokenizer(line, " ");
i++;
}while(st.hasMoreTokens());
} catch(Exception e){System.err.println(e);};