java在读取文件中的下一行和上一行时,我得到一个空指针异常
我知道在逐行读取文件时读取下一行和上一行的方法就像
String prev = null;
String curr = null;
String next = null;
Scanner sc = new Scanner(new File("thefile.txt"));
while(sc.hasNextLine()) {
prev = curr;
curr = next;
next = sc.nextLine();
但是在第一次迭代中,我得到了一个空指针异常,因为我必须处理当前元素
这有什么解决办法
Scanner sc = new Scanner(file);
String curr = null ;
String next = null ;
while (sc.hasNextLine()) {
curr = next;
next = sc.nextLine();
if(curr.length() > 0 && !curr.equals(". O O")) {
lines+= curr.substring(0, curr.indexOf(" ")) + " ";
for(String pat : patStrings)
{
// System.out.println(pat) ;
Pattern minExp = Pattern.compile (pat);
Matcher minM = minExp.matcher(curr);
while(minM.find())
{
String nerType = minM.group(2);
if(nerType.contains("B-NE_ORG")){
if (next.contains("I-NE_ORG"))
orgName+= minM.group(1)+" ";
# 1 楼答案
做
当您进入while循环时,如果文件有两行或更多行,则可以根据您的代码开始处理
# 2 楼答案
我不确定这是否有帮助,但交换curr=next的位置;和next=sc.nextLine(); 您的解决方案:
我的建议是:
# 3 楼答案
您很可能需要先阅读两行,才能正确设置变量
如果您一次需要三行,那么您应该实际阅读三行,然后处理它们