我目前正在编写一个递归下降解析器。代码的目标是判断字符串是否在语言中。我需要读取一个包含多个字符串的文件(每行一个字符串)。目前它仅适用于文件中的第一个字符串,然后写入控制台。我在正确执行此操作时遇到问题,并使其读取每一行而不是第一行。任何帮助表示赞赏。(可能有不同的方法来解决这个问题,因为重写了很多代码以使其更充分......但我现在只是在寻找“简单”的解决方案)
问题所在的代码顶部:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Main
{
static int ptr;
static char[] input;
public static void main(String[] args)
{
String str="";
BufferedReader br = null;
FileReader fr = null;
try {
fr = new FileReader("input.txt");
br = new BufferedReader(fr);
br = new BufferedReader(new FileReader("input.txt"));
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
input = str.toCharArray();
if(input.length < 2)
{
System.out.println("The string '"+str+"' is not in the language.");
System.exit(0);
}
ptr = 0;
boolean isValid = E();
if((isValid) & (ptr == input.length))
{
System.out.println("The string '"+str+"' is in the language.");
}
else
{
System.out.println("The string '"+str+"' is not in the language.");
}
}
static boolean E()
{
int fallback = ptr;
if(input[ptr++] != '|')
{
ptr = fallback;
return false;
}
if(P() == false)
{
ptr = fallback;
return false;
}
if(O() == false)
{
ptr = fallback;
return false;
}
return true;
}
如果可以使用 java8 那么为什么不使用 java nio 来读取所有行呢?https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#readAllLines-java.nio.file.Path-java.nio.charset.Charset-
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句