gpt4 book ai didi

java - 使用正则表达式 Java 搜索字母

转载 作者:行者123 更新时间:2023-12-01 15:13:00 24 4
gpt4 key购买 nike

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)

我尝试了很多,但没有任何效果。

最佳答案

检查下面的代码:

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后继续。

关于java - 使用正则表达式 Java 搜索字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12052162/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com