我有一个关于制作Java语法检查器的任务。它使用java.util.stack,它应该做的是从提供的文件中读取,然后检查语法错误。如何做到这一点的方法是在堆栈中添加一个“令牌”,其中包含字符,行号,行中的位置,是否不匹配或意外以及行本身。
该功能的代码如下:
public static boolean check(String Filename, boolean ConsoleOutput) throws FileNotFoundException
{
mFileName = Filename;
mConsoleOutput = ConsoleOutput;
File mFile = new File("src/Kurien/tests/" + mFileName);
Scanner FileReader = new Scanner(mFile);
if(ConsoleOutput)
{
System.out.println("Processing " + "'" + mFileName + "'" + "\n" + "----------------------");
}
while (FileReader.hasNextLine())
{
mLineNumber++;
mLine = FileReader.nextLine();
for (int counter = 0; counter < mLine.length(); counter++)
{
mCharacter = mLine.charAt(counter);
if (mCharacter == '(')
{
mStack.push(new Token(mCharacter, mLineNumber, counter, ErrorDetail.Unmatched, mLine));
}
else if (mCharacter == '{')
{
mStack.push(new Token(mCharacter, mLineNumber, counter, ErrorDetail.Unmatched, mLine));
}
else if (mCharacter == ')')
{
if (mStack.isEmpty())
{
Error = true;
mStack.push(new Token(mCharacter, mLineNumber, counter, ErrorDetail.Unexpected, mLine));
}
else if (mStack.peek().equals('('))
{
mStack.pop();
}
else
{
Error = true;
mStack.push(new Token(mCharacter, mLineNumber, counter, ErrorDetail.Unexpected, mLine));
}
}
else if (mCharacter == '}')
{
if (mStack.isEmpty())
{
Error = true;
mStack.push(new Token(mCharacter, mLineNumber, counter, ErrorDetail.Unexpected, mLine));
}
else if (mStack.peek().equals('{'))
{
mStack.pop();
}
else
{
Error = true;
mStack.push(new Token(mCharacter, mLineNumber, counter, ErrorDetail.Unexpected,mLine));
}
}
}
}
if(!Error)
{
System.out.println("[SUCCESS]");
}
else
{
while(mStack.iterator().hasNext())
{
Token Temp = (Token)mStack.iterator().next();
if(Temp.mDetail == ErrorDetail.Unexpected)
{
System.out.println("[ERROR] " + Temp.mDetail.toString() + " closing token in file '" + mFileName + "'" + " line#" + Temp.mLineNumber);
System.out.println(mLine);
System.out.println(Spaces(Temp.mLine.length() - Temp.mPosition) + "^");
}
else if(Temp.mDetail == ErrorDetail.Unmatched)
{
System.out.println("[ERROR] + " + Temp.mDetail + "token in file '" + mFileName + "'" + "line#" + Temp.mLineNumber);
System.out.println(mLine);
System.out.println(Spaces(Temp.mLine.length() - Temp.mPosition) + "^");
}
}
}
return Error;
}
private static class Token
{
char mCharacter;
int mLineNumber;
int mPosition;
ErrorDetail mDetail;
String mLine;
Token(char Character, int LineNumber, int Position, ErrorDetail Detail, String Line)
{
mCharacter = Character;
mLineNumber = LineNumber;
mPosition = Position;
mDetail = Detail;
mLine = Line;
}
}
}
现在,第一个测试用例的预期输出如下:
[ERROR] Unexpected closing token in file 'test1.txt' line#7:
}
^
但我得到的是以下内容:
[ERROR] + Unmatchedtoken in file 'test1.txt'line#1
我知道格式化可以很好地调整,但是这里显然存在另一个问题,我无法完全按手指。