我被分配一个项目,实现自上而下的回溯解析器只包含一个在其重写规则的RHS非终结符(如的S - > AASB | AASA | ASA)任何语法自上而下解析 - Java的
到目前为止,我有三种方法,包括main
,用于处理检查输入字符串的有效性。
我的目标是,使用char[][]
数组作为语法,检查输入字符串中的每个字符是否符合语法,如果字符串包含在语法中,则返回true
。
public class TDBP {
public static void main(String[] args) {
char[][] g = new char[][]
{ {'a', 'a', 'S', 'b'},
{'a', 'a', 'S', 'a'},
{'a', 'S', 'a'},
{'\0'} };
SP(g);
}
public static void SP(char[][] g) {
Scanner s = new Scanner(System.in);
boolean again = true; int pn = 0;
String test;
while(again) {
System.out.print("Next string? ");
test = s.nextLine();
if(S(pn, test, g))
System.out.println("String is in the language");
else
System.out.println("String is not in the language");
if(s.nextLine() == "\n") again = false;
}
s.close();
}
public static boolean S(int pn, String test, char[][] g) {
char[] c = test.toCharArray();
boolean exists = false;
for(int i = pn; i < g.length; i++) {
for(int j = 0; j < g[i].length; j++) {
if(c[j] == 'S')
S(++pn, test, g);
if(c[j] == g[i][j])
exists = true;
}
}
return exists;
}
}
在我的算法,pn
是一个整数跟踪其生产我目前看语法,并确保我不扫描相同的语法两次(如1的pn
在上面的语法中将对应于aaSa
)。另外,我有\0
代表空字符串。
我正确解析字符串吗?
谢谢!
这个问题需要细化,你有什么问题? – 2014-11-21 05:00:03
我的方法是检查字符串'test'中每个字符的有效性是否正确? – Delfino 2014-11-21 05:05:46
然后编辑你的问题更具体 – 2014-11-21 05:15:51