使用正则表达式Java搜索字母
我需要帮助的问题是:使用正则表达式Java搜索字母,java,Java,我需要帮助的问题是: 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 sta
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)
如果您获得了
FileNotFoundException
,那么您将在上面一行获得NullPointerException
,因为您在捕获异常FileNotFoundException
后将继续,这一行上有一个NullPointerException:
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
//.....
}
这意味着您的扫描仪sc
未初始化。如果找不到该文件并抛出FileNotFoundException
,则会发生这种情况。由于在catch块中没有执行任何操作,因此无法查看是否引发了此类异常
试试这个:
String word = sc.next();
我认为有空的捕集区是一个非常糟糕的主意。尝试至少打印一次,以了解是否捕捉到异常。我的问题是我不知道哪一行是第28行。我认为突出显示这一行将帮助很多人帮助您:-)我想可能是
扫描仪sc
因为找不到文件而为空。我建议您在catch块中打印一条消息,并将以下所有代码放在try块中。很抱歉,我不太擅长此操作,但我应该将此代码放在第28行和下一行之间?
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();
}
}