0
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)

我已经尝试了很多,但没有任何真正的工作..

4

2 回答 2

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

于 2012-08-21T09:47:31.043 回答
0

你在这一行有一个 NullPointerException :

String word = sc.next();

这意味着您Scanner sc的未初始化。如果找不到文件并抛出 a ,就会发生这种情况。您看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 块是一个非常糟糕的主意。尝试至少打印一次以了解是否捕获异常。

于 2012-08-21T09:53:57.057 回答