我正在开发这个java程序,它是一个递归下降解析器。下面提供的输出不包含任何语法错误,但程序打印错误消息。程序应该打印“SUCCESS: ...”,但却打印“ERROR: ...”。这是我的代码:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Main {
private static BufferedReader reader;
private static String token;
public static void main(String[] args) {
String inputFile = "input1.txt"; // Specify the input file name here
try {
reader = new BufferedReader(new FileReader(inputFile));
token = getNextToken();
if (parse()) {
System.out.println("SUCCESS: the code has been successfully parsed.");
} else {
System.out.println("ERROR: the code contains a syntax mistake.");
}
reader.close();
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
}
}
private static String getNextToken() throws IOException {
return reader.readLine(); // Read the next line from the file
}
private static boolean parse() throws IOException {
if (!token.equals("{")) {
return false; // Program should start with "{"
}
while (!token.equals("$")) {
if (!token.equals("compute")) {
return false; // Expecting "compute" token
}
if (!isValidComputeStatement()) {
return false; // Invalid compute statement
}
}
return true; // Parsing successful
}
private static boolean isValidComputeStatement() throws IOException {
token = getNextToken(); // Move to the next token
if (!token.equals(":")) {
return false; // Expecting colon after "compute"
}
token = getNextToken(); // Move to the next token
if (!isValidAssignmentStatement()) {
return false; // Invalid assignment statement
}
return true; // Valid compute statement
}
private static boolean isValidAssignmentStatement() throws IOException {
if (!token.equals("id")) {
return false; // Expecting an identifier (variable name)
}
token = getNextToken(); // Move to the next token
if (!token.equals("=")) {
return false; // Expecting "=" after the identifier
}
token = getNextToken(); // Move to the next token
if (!token.equals("num")) {
return false; // Expecting a number after "="
}
token = getNextToken(); // Move to the next token
if (!token.equals(";")) {
return false; // Expecting ";" to terminate the statement
}
token = getNextToken(); // Move to the next token
return true; // Valid assignment statement
}
}
这是输入的txt文件(每一行是一个标记):
{
compute
:
id
=
num
;
compute
:
id
=
num
;
compute
:
id
=
id
+
id
;
compute
:
id
=
id
-
id
;
call
:
id
(
id
,
num
,
id
)
;
}
$
谢谢你。
这不是火箭科学,但你的代码是完全错误的。它不验证文件的架构。给你一个可行的解决方案让你意识到解决这个任务的方法比解释你的代码中的问题更容易。
我不确定我的解决方案是否正确,但它非常适合您输入的示例。
100%