我正在重新进行练习考试,而且我几乎已经完成了。我唯一的问题是这部分:
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|
读取文件后,我必须使用 2d int 数组构建矩阵,我使用了另一个练习中的相同代码,但是当使用 stk.nextToken() 时,我在 java.util.StringTokenizer.nextToken(未知来源) 处得到 java.util.NoSuchElementException
我找不到错误,二维数组已正确初始化和填充。
预先感谢您的帮助。
最佳答案
异常的“未知来源”部分是通过 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++;
关于java - stk.nextToken() 返回错误 "Unknown Source",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14440115/