Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/350.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中修复NullPointerException的问题—想想看';这是一个初始化问题,但可以';我找不到_Java_Nullpointerexception - Fatal编程技术网

在Java中修复NullPointerException的问题—想想看';这是一个初始化问题,但可以';我找不到

在Java中修复NullPointerException的问题—想想看';这是一个初始化问题,但可以';我找不到,java,nullpointerexception,Java,Nullpointerexception,我已经阅读了许多其他的NPE解决方案,我也尝试过实现其他的建议,但是没有一个完全符合我的想法,这只会导致更多的eclipse错误。我已经编译并尝试从命令行运行,当在命令行运行时,给我正在运行的应用程序一些字符串。下面是main类,以及包含main正在使用的方法的类 使用main方法初始化: package my.package.ext; public class WordCounterApp { /** * @param args * Two command

我已经阅读了许多其他的NPE解决方案,我也尝试过实现其他的建议,但是没有一个完全符合我的想法,这只会导致更多的eclipse错误。我已经编译并尝试从命令行运行,当在命令行运行时,给我正在运行的应用程序一些字符串。下面是main类,以及包含main正在使用的方法的类

使用main方法初始化:

package my.package.ext;



public class WordCounterApp {

    /**
     * @param args
     * Two command line arguments: the first one needs to be in quotes, the string that will be used, the second optional argument
     * is the unique word to be counted (countWord method).
     * @param source 
     * @param word 
     */
    public static void main(String[] args) {
        String source = null;
        String uniqueword = null;
        StringBuilder word = null;
        WordCounter counter = new WordCounter(source, word);
        WordCounter uniqueCounter = new WordCounter(source, uniqueword);
        counter.countWords(source);
        counter.countUniqueWords(source);
        uniqueCounter.countWord(source, uniqueword);

}

}
public static void main(String[] args) {
        String source = null;
        // ... a few lines
        counter.countWords(source);
        // ... more code

}
使用其他方法初始化:

package my.package.ext;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.lang.Character;
import java.lang.StringBuilder;

public class WordCounter {
    public Integer counter = 0;
    public String source;
    public HashSet<String> hashset;
    public StringBuilder word;
    public String uniqueword;

    public WordCounter(String source) {
         counter = new Integer(counter);
    }
    public WordCounter(String source, StringBuilder word) {
         counter = new Integer(counter);
    }
    public WordCounter(String source, String uniqueword) {
        counter = new Integer(counter);
    }
    /**
     *  
     * @param line - the string parameter to get a total word count from.
     */

    public int countWords(String source) {

        boolean word = false;
        int endOfLine = source.length() - 1;
        Integer counter = 0;

        for (int i = 0; i < source.length(); i++) {
            if (Character.isLetter(source.charAt(i)) == true && i != endOfLine) {
                word = true;
            //} else if (Character.charValue(line.charAt(i)) == "-" && i != endOfLine) {
            //  word = true;
            } else if (Character.isLetter(source.charAt(i)) == false && word == true) {
                counter++;
                word = false;
            } else if (Character.isLetter(source.charAt(i)) && i == endOfLine) {
                counter++;
            }
        }
        System.out.println(counter);
        return counter;
    }




/**
 * 
 * @param line - the string parameter that we will return the unique word count from. Randy recommends a HashSet.
 * Put it into a hashset. Hashsets don't allow duplicate elements. Then do a count. 
 */

    public int countUniqueWords(String line) {
        hashset = new HashSet<String>();
        word = new StringBuilder();
        int endOfLine = line.length() - 1;
        boolean isWord = false;
        String stringWord = null;
        Integer counter = 0;

        for (int i = 0; i < line.length(); i++) {
            if (Character.isLetter(line.charAt(i)) == true && i != endOfLine) {
                //System.out.println(i);
                word.append(line.charAt(i));
                isWord = true;
            } else if (Character.isLetter(line.charAt(i)) == false && isWord == true) {
                counter++;
                //System.out.println("Counter is: " + counter);
                stringWord = word.toString();
                //System.out.println("stringWord is now: " + stringWord);
                hashset.add(stringWord);
                //System.out.println(hashset);
                word = new StringBuilder();
                isWord = false;
            } else if (Character.isLetter(line.charAt(i)) && i == endOfLine) {
                counter++;
                stringWord = word.toString();
                hashset.add(stringWord);
            }
        }
        //System.out.println(counter);
        System.out.println("There are " + hashset.size() + " unique words in this string");
        System.out.println("These are the unique words in the string: " + hashset);
        return counter;

    }


/**
 * 
 * @param source - the string the word is to be counted from
 * @param word - the word to be counted
 * 
 */
    public void countWord(String source, String word) {

        String str = source;
        Pattern p = Pattern.compile("\\s"+word+"\\s");
        Matcher m = p.matcher(str);
        int count = 0;
        while (m.find()) {
            count++;
        }
        System.out.println("The word: " + "\"" + word + "\"" + " appears " + count + " times.");
        }

}
所以看看这个,我觉得我没有正确初始化源代码。我试过类似的方法 WordCounter源=新的WordCounter()

但我尝试的每一个变体,引入正确的构造函数,都会给我带来其他eclipse错误。我似乎到不了那里,恐怕我走错了路。我可能还有其他的问题。在传入一些字符串作为参数以提供方法时,我也不确定从命令行运行的正确方式。提前感谢

您的主要方法:

package my.package.ext;



public class WordCounterApp {

    /**
     * @param args
     * Two command line arguments: the first one needs to be in quotes, the string that will be used, the second optional argument
     * is the unique word to be counted (countWord method).
     * @param source 
     * @param word 
     */
    public static void main(String[] args) {
        String source = null;
        String uniqueword = null;
        StringBuilder word = null;
        WordCounter counter = new WordCounter(source, word);
        WordCounter uniqueCounter = new WordCounter(source, uniqueword);
        counter.countWords(source);
        counter.countUniqueWords(source);
        uniqueCounter.countWord(source, uniqueword);

}

}
public static void main(String[] args) {
        String source = null;
        // ... a few lines
        counter.countWords(source);
        // ... more code

}
由此产生的错误:

public int countWords(String source) {
    boolean word = false;
    int endOfLine = source.length() - 1;  //the source of the NPE is this line
    Integer counter = 0;
}

发生这种情况的原因是,
source
null

您的主方法中的
source
字符串为
null
,并且您将其作为参数传递给
countWords
方法

 public static void main(String[] args) {
        String source = null;// it is null here
        ..............
        ............
        counter.countWords(source);// passing null here
因此,在你呼唤的时候

    int endOfLine = source.length() - 1;
由于源为null,它将抛出NullPointerException

初始化字符串以摆脱NPE

编辑:如果要将源作为命令行参数传递

String source =args[0];

并在运行时传递命令行参数。

将null作为source传递,稍后调用source.length。这导致NPE。

计数器。countWords(源)


这里源字符串为null,导致NPE。

在主方法中,您将
指定为
null
。您从未将其重新分配给任何其他对象,因此,当您调用
counter.countWords(source)
时,它相当于调用
counter.countWords(null)

这意味着,当您到达
countWords()
中试图调用
source.length()
的行时,
source
实际上是
null
,从而引发
NullPointerException
。为了避免这种情况,在调用该方法之前,必须将
指定为某物。

City17Mogul

我停止阅读您的main方法,因为我已经找到了一个show stopper:您根本没有使用
args
(传递到main方法的命令行参数)。。。因此,您的
源代码
uniqueWord
word
变量总是
null
。。。我认为这是您的
NullPointerException
的根本原因

你可能还想在谷歌上搜索:如何读取stacktrace。。。这是新程序员必须学习的技能,而且这种技能甚至可以在(几乎所有)现代语言之间移植

stacktrace会准确地告诉您NPE发生在哪一行代码上,从那里通常很容易确定哪些变量为空。。。特别是如果你使用调试器。。。只需在有问题的行上放置一个断点,使用相同的输入重新运行程序,并检查该行上所有变量的值。。。其中一个或多个必须为null


干杯。Keith.

这是我的版本,基于您的“手动行解析”方法:

package forums;

import java.util.List;
import java.util.ArrayList;
import java.util.Set;
import java.util.HashSet;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class WordCounterApp {

    private static void printUsage() {
        System.out.println("usage: java -cp C:\\Java\\home\\classes forums.WordCounterApp <text> [targetWord]");
        System.out.println("   <text> is a quoted string to be split into words.");
        System.out.println("   optional [targetWord] to be counted seperately.");
    }

    /**
     * @param args
     *  REQUIRED [0] text: a quoted string to be searched for words. 
     *  OPTIONAL [1] targetWord: the word to be counted, if desired.
     */
    public static void main(String[] args) {
        if (args.length==0) {
            printUsage();
            return;
        }
        String text = args[0];
        String targetWord = args.length>1 ? args[1] : null;
        WordCount wordCount = new WordCount(text);

        System.out.println();

        // all words in this string
        List<String> words = wordCount.all();
        System.out.println("There are "+words.size()+" words in the string. That are:\n"+words);
        System.out.println();

        // unique words in this string
        Set<String> uniqueWords = wordCount.unique();
        System.out.println("There are "+uniqueWords.size()+" unique words in the string. They are:\n"+uniqueWords);
        System.out.println();

        // the number of occurrences of the target word in this string, if given
        if (targetWord ! = null) {
            int targetCount = wordCount.of(targetWord);
            System.out.println("The word \""+targetWord+"\" appears "+targetCount+" times.");
            System.out.println();
        }

    }
}

/**
 * Counts the words on a line, in various ways.
 */
class WordCount 
{
    private final String _line;
    public WordCount(String line) {
        _line = line;
    }

    public List<String> all() {
        final List<String> results = new ArrayList<String>(64); // just a guess at max word-count.
        final Matcher matcher = Pattern.compile("\\w+").matcher(_line);
        int count = 0;
        while ( matcher.find() )
            results.add(matcher.group());
        return results;
    }

    /**
     * Returns a set of the unique words in the line
     */
    public Set<String> unique() {
        final HashSet<String> results = new HashSet<String>();
        final int lineLength = _line.length();
        final int endOfLine = lineLength-1;
        final StringBuilder wordBuffer = new StringBuilder(16); // just a guess at max-word-length
        char ch;
        boolean isInWord = false;
        // foreach character in the line EXCEPT the last one:
        for ( int i=0; i<endOfLine; ++i ) {
            ch = _line.charAt(i);
            if ( Character.isLetter(ch) ) {
                // we're at the start or continuation of the current word.
                wordBuffer.append(ch);
                isInWord = true;
            } else if ( isInWord ) {
                // we're reached the end-of-word, or the end-of-the-line.
                results.add(wordBuffer.toString());
                wordBuffer.setLength(0); // clear the word-buffer.
                isInWord = false;
            }
        }
        // handle the last character in the line seperately, just to save
        // testing for it everytime through the loop... and I personally 
        // think that the logic is easier to follow this way.
        ch = _line.charAt(endOfLine);
        if ( Character.isLetter(ch) )
            wordBuffer.append(ch);
        if ( wordBuffer.length() > 0 )
            results.add(wordBuffer.toString());
        return results;
    }

    /**
     * Returns the number of occurences of the targetWord.
     * @param targetWord - the word to be counted.
     */
    public int of(String targetWord) {
        final String regex = "\\s+"+targetWord+"\\s+";
        final Matcher matcher = Pattern.compile(regex).matcher(_line);
        int count = 0;
        while ( matcher.find() )
            ++count;
        return count;
    }

}
套餐论坛;
导入java.util.List;
导入java.util.ArrayList;
导入java.util.Set;
导入java.util.HashSet;
导入java.util.regex.Pattern;
导入java.util.regex.Matcher;
公共类WordCounterApp{
私有静态void printUsage(){
System.out.println(“用法:java-cp C:\\java\\home\\classes forums.WordCounterApp[targetWord]”;
System.out.println(“是要拆分为单词的带引号的字符串。”);
System.out.println(“可选的[targetWord]单独计数”);
}
/**
*@param args
*必需的[0]文本:要搜索单词的带引号的字符串。
*可选[1]目标词:如果需要,要计数的字。
*/
公共静态void main(字符串[]args){
如果(参数长度==0){
打印用法();
返回;
}
字符串text=args[0];
字符串targetWord=args.length>1?args[1]:null;
WordCount WordCount=新的字数(文本);
System.out.println();
//此字符串中的所有单词
List words=wordCount.all();
System.out.println(“字符串中有“+字.size()+”字,即:\n”+字);
System.out.println();
//此字符串中的唯一单词
设置uniqueWords=wordCount.unique();
System.out.println(“字符串中有“+uniqueWords.size()+”个唯一单词,它们是:\n”+uniqueWords);
System.out.println();
//目标词在此字符串中出现的次数(如果给定)
if(targetWord!=null){
int targetCount=wordCount.of(targetWord);
System.out.println(“单词\”+targetWord+“\”出现“+targetCount+”次”);
System.out.println();
}
}
}
/**
*以各种方式计算一行中的单词。
*/
类字数
{
私有最终字符串_行;
公共字数(字符串行){
_直线=直线;
}
公共列表全部(){
final List results=new ArrayList(64);//只是猜测一下最大字数。
final Matcher Matcher=Pattern.compile(\\w+).Matcher(\u行);
整数计数=0;
while(matcher.find())
results.add(matcher.group());
返回结果;
}
/**
*返回行中的一组唯一单词
*/
公共集唯一(){
最终HashSet结果=新HashSet();
final int lineLength=_line.length();
最终int endOfLine=线宽-1;