我目前正在编写一个递归下降解析器。代码的目标是判断字符串是否属于该语言。我需要读取一个包含多个字符串的文件(每行一个字符串)。目前它仅适用于文件中的第一个字符串,然后写入控制台。我在正确执行此操作并使其读取每一行而不是第一行时遇到问题。任何帮助表示赞赏。 (可能有不同的方法来解决这个问题,例如重写大量代码以使其更加充分......但我现在只是在寻找“简单”的解决方案)
问题所在的代码顶部部分:
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-
关于java - 更正输入文件以读取每一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44768973/