0

我正在尝试读取一个文件并弄清楚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;
}

有人可以帮我解决这个问题。

4

3 回答 3

0

请按如下方式编写您的构造函数;

   Client c;

  public Jail(Client c) {
     if(c == null) {
         c = new Client();
     }
  }
于 2012-06-18T08:39:17.500 回答
0

在我看来,cinc.playerName是空的。

还取决于FileUtil您使用的内容,这也可能导致 aNullPointerException何时playerName为空。

于 2012-06-18T00:16:48.820 回答
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");
于 2012-06-18T00:17:14.833 回答