我在用Java编写的简单解析器中遇到了麻烦。这个解析器正在解析字符串,而不是将令牌保存到arraylist,而不是解析器处理令牌(例如' PUT'或者' STRING:...')
那是我的代码:
package net.ruza;
import java.util.*;
public class SimpleParser
{
public static void main(String[] args)
{
SimpleParser simpleParser = new SimpleParser();
Scanner sc = new Scanner(System.in);
String input = "###";
List<String> data = new ArrayList<String>();
while (input.length() > 1)
{
input = sc.nextLine();
data.addAll(simpleParser.lex(input));
}
for (String s : data)
{
System.out.println(s);
}
simpleParser.parse(data);
}
public List<String> lex(String parse)
{
List<String> tokens = new ArrayList<String>();
boolean stringFound = false;
StringBuilder string = new StringBuilder();
StringBuilder tok = new StringBuilder();
for (char c : parse.toCharArray())
{
tok.append(c);
if (tok.toString().equals("put"))
{
tokens.add("PUT");
tok = new StringBuilder();
}
else if (tok.toString().equals(" ") && !stringFound)
{
tok = new StringBuilder();
}
else if (!stringFound && (tok.toString().equals("\"") || tok.toString().equals("'")))
{
stringFound = true;
tok = new StringBuilder();
System.out.println("String found!");
}
else if (stringFound && (tok.toString().equals("\"") || tok.toString().equals("'")))
{
tokens.add("STRING:'" + string.toString() + "'");
System.out.println("String end!");
tok = new StringBuilder();
string = new StringBuilder();
stringFound = false;
}
else if (stringFound)
{
string.append(c);
tok = new StringBuilder();
}
}
return tokens;
}
public void parse(List<String> tokens)
{
System.out.println("Parser invoked!");
boolean putNext = false;
for (String s : tokens)
{
if (s.equals("PUT"))
{
putNext = true;
}
else if (putNext && (s.substring(0, 5).equals("STRING") || s.substring(0, 2).equals("NUM")))
{
doPrint(s);
}
else System.err.println("Invalid token!");
}
}
public void doPrint(String toPrint)
{
if (toPrint.substring(0, 5).equals("STRING"))
System.out.println(toPrint.substring(7, toPrint.length() - 1));
else if (toPrint.substring(0, 2).equals("NUM"))
System.out.println(toPrint.substring(4, toPrint.length() - 1));
else System.err.println("Invalid printable!");
}
}
如何使代码正常工作(例如令牌= {&#34; PUT&#34;,&#34; STRING:&#39;嗨!&#39;&#34;} - &gt;打印& #39;您好&#39;!..)
我很乐意回答!
答案 0 :(得分:0)
我得到了它!这是因为过于有条件的处理。
我需要删除一些&#39; if&#39;声明,它会在一段时间后开始工作。