public static void main(String[]args){
**exp("^[a[k][t][l]]{6}$"); //line 9**
exp("^(bEt).*(oc)$");
exp("^(bEt)$");
exp("^(a).*");
exp("bEt(oc)*");
exp("^(bEt).*");
exp [baba][bebe][bibi][bobo][bubu][fafa][fefe][fofo][fufu]
}
public static void exp(String uttryck){
int counter = 0;
File fil = new File("Walta_corpus1.txt");
Scanner sc = null;
try{
sc = new Scanner(fil);
}
catch(FileNotFoundException foo){
}
**String word = sc.next();** line 28
Pattern pattern = Pattern.compile(uttryck);
Matcher matcher = pattern.matcher(word);
while(word != null){
if(matcher.find()){
counter++;
System.out.println(word);
}
if(sc.hasNext()){
word=sc.next();
matcher = pattern.matcher(word);
}
else
word = null;
}
System.out.println(counter);
}
我需要帮助的问题是:
Exception in thread "main" java.lang.NullPointerException
at raknare.exp(raknare.java:28)
at raknare.main(raknare.java:9)
我已经尝试了很多,但没有什么真正有效..
答案 0 :(得分:1)
检查以下代码:
public static void exp(String uttryck) throws FileNotFoundException{
// .....
try{
sc = new Scanner(fil);
}
catch(FileNotFoundException foo){
// if scanner throws exception, sc is null
foo.printStackTrace(); // add this method call and check.
throw foo; //rethrow exception to caller
}
String word = sc.next(); // if catch is executed, sc will give NullPointerException
//.....
}
如果您获得FileNotFoundException
,那么您将获得NullPointerException
位于上方的行,因为您在捕获异常FileNotFoundException
后仍在继续。
答案 1 :(得分:0)
这一行有一个NullPointerException:
String word = sc.next();
这意味着您的Scanner sc
未初始化。如果你找不到文件并且抛出了FileNotFoundException
,就会发生这种情况。你无法看到是否抛出了这样的异常,因为你在catch块中没有做任何事情。
试试这个:
public static void exp(String uttryck){
int counter = 0;
File fil = new File("Walta_corpus1.txt");
Scanner sc = null;
try{
sc = new Scanner(fil);
String word = sc.next();**
Pattern pattern = Pattern.compile(uttryck);
Matcher matcher = pattern.matcher(word);
while(word != null){
if(matcher.find()){
counter++;
System.out.println(word);
}
if(sc.hasNext()){
word=sc.next();
matcher = pattern.matcher(word);
} else
word = null;
}
System.out.println(counter);
} catch(FileNotFoundException foo){
foo.printStackTrace();
}
}
我认为拥有空的catch块是一个非常糟糕的主意。尝试至少打印一个打印件,以了解是否有异常。