我正在使用文本文件处理文件阅读器和编写器。基本上实现了一个帕斯卡语法的 dfa,它将处理程序中的注释。为此,我使用了 3 个文本文件,1 个文件从中读取数据,1 个在其中写入令牌,1 个在其中写入错误令牌。pascal 编译器不会将此 {{ 视为注释,因为注释语法是 "{this is a comment}" 。为此,我使用了 [5][4] 数组,并使用文件阅读器从包含此文本“{a}”的文本文件名“code.txt”中读取。但问题是,当我将其写入一个新的文本文件名“token.txt”(最初将其写入 token.txt 但它应该在 error.tx 中)时,它会打印这个 {{a} 意味着它打印第一个字符两次像 {{ 。我想输出和我在 code.txt 文件中写的一样的输出。
public class Lex {
public static char dfa1[][] = new char[5][4];
/*
* for(int i=0; i<5; i++) { for(int j=0; j<4; j++) {
* System.out.println("arr["+i+"]["+j+"]"+dfa1[i][j]); } }
*/
//FileReader fr = new FileReader(filename);
//BufferedReader br = new BufferedReader(fr);
File file = new File("code.txt");
BufferedReader reader = null;
int StartState = 1;
char CurrentState = '1';
int acp =0;
String temptok = new String();
try {
reader = new BufferedReader(new FileReader(file));
int i;
// repeat until EOF
while ((i = reader.read()) != -1) {
char c = (char) i;
if (c == '{') {
if (CurrentState == dfa1[1][0]) {
CurrentState = '2';
acp =0;
temptok = temptok.concat(String.valueOf(c));
} else if (CurrentState == dfa1[2][0]) {
temptok = temptok.concat(String.valueOf(c));
acp =0;
CurrentState = '4';
} else if (CurrentState == dfa1[3][0]) {
temptok = temptok.concat(String.valueOf(c));
CurrentState = '4';
acp =0;
} else if (CurrentState == dfa1[4][0]) {
temptok = temptok.concat(String.valueOf(c));
acp =0;
break;
}
}
if (c == '}') {
if (CurrentState == dfa1[1][0]) {
acp =0;
temptok = temptok.concat(String.valueOf(c));
break;
} else if (CurrentState == dfa1[2][0]) {
temptok = temptok.concat(String.valueOf(c));
CurrentState = '3';
acp = 1;
} else if (CurrentState == dfa1[3][0]) {
temptok = temptok.concat(String.valueOf(c));
CurrentState = '3';
acp = 1;
} else if (CurrentState == dfa1[4][0]) {
temptok = temptok.concat(String.valueOf(c));
acp = 0;
break;
}
}
if (c != '}') {
if (CurrentState == dfa1[1][0]) {
temptok = temptok.concat(String.valueOf(c));
acp =0;
break;
} else if (CurrentState == dfa1[2][0]) {
temptok = temptok.concat(String.valueOf(c));
CurrentState = '2';
acp =0;
} else if (CurrentState == dfa1[3][0]) {
temptok = temptok.concat(String.valueOf(c));
acp =0;
break;
} else if (CurrentState == dfa1[4][0]) {
temptok = temptok.concat(String.valueOf(c));
acp =0;
break;
}
}
//System.out.println(temptok);
PrintWriter writer = new PrintWriter("token.txt", "UTF-8");
PrintWriter ewriter = new PrintWriter("error.txt", "UTF-8");
if(acp == 1){
writer.println(temptok);
writer.close();
}
else if(acp == 0)
{
ewriter.println(temptok);
ewriter.close();
}