我正在尝试使用以下语法的递归下降解析来检查语法的正确性:
<FACTOR> ::= <EXPR> | i
<TERM> ::= <FACTOR> * <TERM> | <FACTOR>
<EXPR> ::= <TERM> + <EXPR> | <TERM>
问题在于,语法似乎是递归的,因为factor
can be expr
which can be term
which can be factor
。所以似乎不可能使用程序来检查它的正确性。但是我不确定这是正确的,因为这是作为作业给出的。有人可以告诉我它是否正确,如果是真的,我可以用一个可能的算法来检查这个吗?
谢谢。
不知道它是否有帮助,但这是我当前的代码:
//Variable to store our current character index
static int i = 0;
//Variable to store our input string
static String input;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter text to check for correctness: ");
input = scan.nextLine();
if(input.charAt(input.length() - 1) != '#'){
input += scan.nextLine();
}
//Remove all spaces just to prevent space interference
input = input.replaceAll(" ", "");
if(Factor(nextChar()))
{
System.out.println("Your text input is correct");
}
else
{
System.out.println("Your text input does not conform with the grammar");
}
}
public static boolean Factor(char ourChar){
//<factor> ::= <expr> | i
if(ourChar == '#')
{
//If it's # we should bounce back if and return true since no errors yet
return true;
}
if(ourChar == 'i')
{
//if it's i then return true
return true;
}
else{
//so the character is not i, let's check if satisfies the Expr grammar
if(!Expr(ourChar))
{
//oooh, it's not return false!
return false;
}
return true;
}
}
public static boolean Expr(char ourChar){
//<expr> ::= <term> + <expr> | <term>
//Before you can be an expression, you must start with a term
if(!Term(ourChar))
//so it doesn't start with term? Bounce back dear
return false;
if(nextChar() != '+'){
//The next character is not a plus, return false to sender
return false;
}
else
{
//So it's plus? Ok, let's check if the next character is another expr
if(!Expr(nextChar()))
return false;
else
//Everybody satisfied, return true
return true;
}
}
public static boolean Term(char ourChar){
//<term> ::= <factor> * <term> | <factor>
//If the character does not start with a factor bounce back
if(!Factor(ourChar))
return false;
if(nextChar() != '*'){
//Yekpa! The factor is not followed by * so bounce back
return false;
}
else{
//SO, it's a star. Ok, if it's followed by a term, bounce back
if(!Term(nextChar()))
{
return false;
}
//Well, all bouncers satisfied, so return true
return true;
}
}
public static char nextChar(){
i++;
return input.charAt(i - 1);
}