因此,对于一个项目,我正在尝试为从文件中读取的假编程语言创建一个简单的词法分析器。本周早些时候我问了一个问题,询问我如何实现这样的程序,然后回答告诉我:创建一个输入缓冲区和两个输出缓冲区。初始化两个循环并增加它们,直到我找到一个令牌的开始。一旦我找到开始,增加第二个循环直到我找到一个空格或符号,然后使用 case 语句输出到两个输出文件,然后使外部循环等于内部循环并继续扫描。我做了一些研究,这种方法类似于循环和切换方法或“ad hoc”方法。
import java.io.*;
public class Lex {
public static boolean contains(char[] a, char b){
for (int i = 0; i < a.length; i++) {
if(b == a[i])
return true;
}
return false;
}
public static void main(String args[]) throws FileNotFoundException, IOException{
//Declaring token values as constant integers.
final int T_DOUBLE = 0;
final int T_ELSE = 1;
final int T_IF = 2;
final int T_INT = 3;
final int T_RETURN = 4;
final int T_VOID = 5;
final int T_WHILE = 6;
final int T_PLUS = 7;
final int T_MINUS = 8;
final int T_MULTIPLICATION = 9;
final int T_DIVISION = 10;
final int T_LESS = 11;
final int T_LESSEQUAL = 12;
final int T_GREATER = 13;
final int T_GREATEREQUAL = 14;
final int T_EQUAL = 16;
final int T_NOTEQUAL = 17;
final int T_ASSIGNOP = 18;
final int T_SMEICOLON = 19;
final int T_PERIOD = 20;
final int T_LEFTPAREN = 21;
final int T_RIGHTPAREN = 22;
final int T_LEFTBRACKET = 23;
final int T_RIGHTBRACKET = 24;
final int T_LEFTBRACE = 25;
final int T_RIGHTBRACE = 26;
final int T_ID = 27;
final int T_NUM = 28;
char[] letters_ = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D',
'E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','_'};
char[] numbers = {'0','1','2','3','4','5','6','7','8','9'};
char[] symbols = {'+','-','*','/','<','>','!','=',':',',','.','(',')','[',']','{','}'};
FileInputStream fstream = new FileInputStream("src\\testCode.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
BufferedWriter bw1 = new BufferedWriter(new FileWriter(new File("src\\output.txt"), true));
BufferedWriter bw2 = new BufferedWriter(new FileWriter(new File("src\\output2.txt"), true));
String scanner;String temp = "";
int n = 0;
while((scanner = br.readLine()) != null){
for (int i = 0; i < scanner.length(); i++) {
for (int j = 0; j < scanner.length(); j++) {
if(contains(letters_,scanner.charAt(i)) || contains(numbers,scanner.charAt(i)) || contains(symbols,scanner.charAt(i))){
j++;
n++;
if(scanner.charAt(j) == ' ' || scanner.charAt(j) == '\n' || scanner.charAt(j) == '\t'){
}
}
}
}
}
in.close();
}
}
我的问题是如何在找到空格或符号后确定要分配单词的标记。我可以将每个字符放在字符串中的 ws 和符号之前并像这样进行比较吗?我尝试过类似的方法,但它把我的整个输入文件写入了字符串,所以我的标记在我的 switch 语句中不匹配。同样使用这种方法,我怎样才能安全地忽略评论和评论块,因为它们不应该被标记化。