我不断收到这个错误java.util.NoSuchElementException
找不到行
当我使用这种方法
public boolean hasMoreCommands() {
if (input.hasNextLine()) {
return true;
} else {
//input.close();
return false;
}
}
public void advance() {
String str;
if(hasMoreCommands() == true){
do {
str = input.nextLine().trim();
// Strip out any comments
if (str.contains("//")) {
str = (str.substring(0, str.indexOf("//"))).trim();
}
} while (str.startsWith("//") || str.isEmpty() || hasMoreCommands());
command = str;
}
}
我在这里有主要代码:
public class Ptest
{
public Ptest(String fileName)
{
String line = null;
String nName = fileName.replace(".vm", ".asm");
Parser p = new Parser();
try{
File neF = new File(nName);
if(!neF.exists()){
neF.createNewFile();
}
File tempFile = new File("temp.txt");
if(!tempFile.exists()){
tempFile.createNewFile();
}
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter(nName);
BufferedWriter bw = new BufferedWriter(fw);
FileWriter writR = new FileWriter(tempFile);
BufferedWriter buffR = new BufferedWriter(writR);
while((line = br.readLine()) != null) {
buffR.write(line+ "\n");
//System.out.println(line);
}
buffR.flush();
buffR.close();
p.insertTitle(tempFile);
String ctype = p.commandType();
int len = ctype.length();
int spaces = 13 - len;
String sp = " ";
String asp = " ";
String a1 = null;
int a2;
int alen;
boolean t = false;
while(p.hasMoreCommands()){
for(int i= 0; i < spaces; i++){
sp += " ";
}
t = p.hasMoreCommands();
a1 = p.arg1();
alen = (10 - a1.length());
for(int i= 0; i < alen; i++){
asp += " ";
}
//a2 = p.arg2();
if (ctype == "C_PUSH" || ctype == "C_POP" || ctype == "C_FUNCTION" || ctype == "C_CALL") {
a2 = p.arg2();
bw.write(ctype + sp + a1 + asp + a2);
}
else {
bw.write(ctype + sp + a1);
}
p.advance();
ctype = p.commandType();
len = ctype.length();
spaces = 13 - len;
}
bw.flush();
bw.close();
}
catch(FileNotFoundException ex){
System.out.println("File not found!");
}
catch(IOException ex){
System.out.println("Error reading file '" + fileName + "'");
}
}
}
我经历了调试器,从字面上看整个文件,然后在完成时给我一个错误。
最佳答案
像@hfontanez一样,我认为您的问题出在此代码中:
if(hasMoreCommands() == true){
do {
str = input.nextLine().trim();
// Strip out any comments
if (str.contains("//")) {
str = (str.substring(0, str.indexOf("//"))).trim();
}
} while (str.startsWith("//") || str.isEmpty() || hasMoreCommands());
command = str;
}
但是,我的解决方案是将while子句更改为
while (str.isEmpty() && hasMoreCommands());
我假设“ advance”应该返回下一个非注释/空白行。
如果上一遍的字符串为空(去掉任何注释后),只要不是最后一行,它将再次绕过循环。但是,如果那是最后一行或str中仍然有内容,那么它将退出循环。注释应该已经删除,因此暂时无需进行测试。
我认为,如果仅在循环中测试hasNextLine,那么如果最后一行是comment /空白,它将永远不会退出循环。