我正在做一个练习的考试,我已经基本完成了。我唯一的问题是这个部分:
int z=0,x=0;
String line="";
RandomAccessFile read = new RandomAccessFile(s, "rw");
while((read.readLine())!=null)
z++;
read.seek(0);
while(x<z){
line=read.readLine();
StringTokenizer stk = new StringTokenizer(line, " ");
if(line.charAt(0)=='r'){
nr=z;
nc=stk.countTokens()-1;
valori = new int[nr][nc];
while(stk.hasMoreTokens()){
stk.nextToken();
for(int i=0; i<nr; i++)
for(int j=0; j<nc; j++)
valori[i][j] = Integer.parseInt(stk.nextToken());}
}
else if(line.charAt(0)=='c'){
nr=stk.countTokens()-1;
nc=z;
valori = new int[nr][nc];
while(stk.hasMoreTokens()){
stk.nextToken();
for(int i=0; i<nr; i++)
for(int j=0; j<nc-1; j++)
valori[j][i] = Integer.parseInt(stk.nextToken());}
}x++;基本上,我必须读取一个文件,其中包含矩阵的描述,如下所示:
c 0 1 0
c 0 0 1
c 0 0 0
c 1 0 0得到的矩阵将是
|0|0|0|1|
|1|0|0|0|
|0|1|0|0|在读取文件后,我必须使用2dint数组构建矩阵,我使用了另一个练习中的相同代码,但在使用stk.nextToken()时,我在java.util.StringTokenizer.nextToken(未知源)中获得了java.util.NoSuchElementException。
我找不到错误,2d数组已正确初始化和填充。
提前感谢您的帮助。
发布于 2013-01-21 21:56:32
异常的“未知源”部分是通过jre而不是JDK运行代码的效果。如果您使用JDK运行,您的运行时环境将能够访问调试信息,并且将打印正确的行号。
快速查看一下就会发现这个部分是错误的: nr=stk.countTokens()-1;nc=z;//z ==行数
//first pass through = hasMoreTokens == true (a total of 4: C,0,1,0)
while(stk.hasMoreTokens()){
//first token - C
stk.nextToken();
//this will iterate 3 times
for(int i = 0; i < nr; i++)
//this, too, will iterate 4 times - a total of 12 times considering
// the outer loop
for(int j = 0; j < nc-1; j++)
// after 3 passes, this will throw the exception
valori[j][i] = Integer.parseInt(stk.nextToken());}
}x++;发布于 2013-01-21 21:57:30
这个错误意味着StringTokenizer中没有更多的令牌了,您正在请求另一个令牌。“未知来源”与您的问题无关-这只是意味着您无法访问Java系统库的源代码,但我怀疑它是否会有所帮助。
发生这种情况是因为您从文件中读取的行包含的空格分隔标记比您预期的要少。
发布于 2013-01-21 22:24:58
出现这个错误是因为您标记了一行,而在两个for循环中,您正在读取列和行。我建议使用.split命令,而不是使用带有while循环的StringTokenizer:
int j=0;
// read all rows
while((read.readLine())!=null) {
String line=read.readLine();
String[] columns=line.split(" ");
// read columns of each row
int i=0;
for (String column: columns) {
if (!column.equals("c")) {
valori[j][i] = Integer.parseInt(column);
}
i++;
}
j++;
}PS:上面的伪代码,未经测试。
https://stackoverflow.com/questions/14440115
复制相似问题