Java - NullPointerException,只需读取文件并返回int

时间:2012-06-18 00:13:39

标签: java nullpointerexception filereader

我正在尝试读取文件,并计算出该文件中出现String的次数。根据多少次,它将向玩家显示不同的对话(这是一个游戏)。这是我的代码

/**
 * Selects which dialogue to send depending on how many times the player has been jailed
 * @return The dialogue ID
 */
public static int selectChat() {
    System.err.println("Got to selectChar()");
    FileUtil.stringOccurrences(c.playerName, // NULLPOINTER HAPPENS HERE
        "./data/restrictions/TimesJailed.txt");

    if (FileUtil.stringCount == 1)
        return 495;
    if (FileUtil.stringCount == 2)
        return 496;
    if (FileUtil.stringCount >= 3) {
        return 497;
    }

    return 0;
}

然后这是实际的文件读取方法

public static int stringCount;

/**
 * @param string
 * @param filePath
 * @return How many occurrences of the string there are in the file
 */
public static int stringOccurrences(String string, String filePath) {
    int count = 0;

    try {
        FileInputStream fstream = new FileInputStream(filePath);
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;

        while ((strLine = br.readLine()) != null) {
            if (strLine.contains(string))
                count++;
        }

        in.close();
    }
    catch (Exception e) { // Catch exception if any
        System.err.println("Error: " + e.getMessage());
    }

    System.err.println(count);
    stringCount = count;
    return count;
}

以下是我对c

所做的一切
Client c;

public Jail(Client c) {
    this.c = c;
}

有人可以帮我解决问题。

3 个答案:

答案 0 :(得分:0)

在我看来,c中的c.playerName为空。

同样取决于您使用的FileUtil,当NullPointerException为空时,也可能导致playerName

答案 1 :(得分:0)

根据我的判断,您的stringOccurrences方法无法抛出NPE - 它不会在try / catch块之外进行解除引用。

您在哪里为c分配值?如果为空,则您尝试阅读c.playerName会产生NullPointerException。要确定是否发生这种情况,请将代码更改为:

String myPlayerName = c.playerName; //now does NPE happen here ...
FileUtil.stringOccurrences(myPlayerName, // or here?
        "./data/restrictions/TimesJailed.txt");

答案 2 :(得分:0)

请编写如下构造函数;

   Client c;

  public Jail(Client c) {
     if(c == null) {
         c = new Client();
     }
  }
相关问题