NullPointerExcetion Native Method Accessor… Hashing Words Issue

强颜欢笑 提交于 2019-11-29 18:09:37

This whileloop is strange:

while (scanner.hasNextLine()) {
    String line = scanner.nextLine();
    while (line != null) {
       String word = scanner.next();
       addWord(word, linecount);
    }
    linecount++;
}

If your input file is:

a
b

Then scanner.nextLine() would be return a, then scanner.next() would return b, because nextLine returns the next end-line delimited String, and next returns the next token from the input file. Is this really what you want? I'd suggest trying this:

while (scanner.hasNextLine()) {{
    String word = scanner.nextLine();
    addWord(word, linecount);

    linecount++;
}

Keep in mind that this would only work if there's only a word per line. If you want to handle multiple words per line, it'd be slightly longer:

while (scanner.hasNextLine()) {{
    String line = scanner.nextLine();

    Scanner lineScanner = new Scanner(line);
    while(lineScanner.hasNext()) {
        addWord(lineScanner.next(), linecount);
    }

    linecount++;
}

There are two different problems here: 1. Your main method is not static. 2. DrJava, the IDE you are using, is not showing a good error message.

As to problem 1, if you add static to the declaration of words, addWord, and main, you will be able to run your program.

The bad error message, problem 2, is a result of a bug in DrJava's "run" command, which is supposed to be able to run both Java programs and Java applets. To address 2., I have filed a bug report at DrJava's SourceForge page. We'll fix that bug soon.

I'm sorry for the inconvenience.

You posted this in a comment:

java.lang.NullPointerException
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
 at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) 
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) 
 at java.lang.reflect.Method.invoke(Unknown Source) 
 at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:27‌​1)

It looks like you are using a non-standard Java compiler. Try compiling this with Sun's or IBM's javac to see if it gives you a different trace. If it does then it might just be an error with your university's implementation of javac.

I mention this as the use of the JavacCompiler class is suspicious for your code's runtime execution.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!