Java-NullPointerException,而只是读取文件并返回int
我试图读取一个文件,并计算该文件中出现Java-NullPointerException,而只是读取文件并返回int,java,nullpointerexception,filereader,Java,Nullpointerexception,Filereader,我试图读取一个文件,并计算该文件中出现字符串的次数。根据次数的不同,它将向玩家显示不同的对话(这是一个游戏)。这是我的密码 /** * 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
字符串的次数。根据次数的不同,它将向玩家显示不同的对话(这是一个游戏)。这是我的密码
/**
* 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;
}
有人能帮我解决这个问题吗。我觉得c.playerName
中的c
是空的
同样取决于您使用的FileUtil
,当playerName
为null时,这也可能会导致NullPointerException
异常。您的stringoccurrencess
方法无法抛出我所知的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");
请写下你的构造器如下
Client c;
public Jail(Client c) {
if(c == null) {
c = new Client();
}
}
在执行FileUtil.StringOccurrences(..)之前,请尝试打印出c.playerName是否为null(System.out.println(c.playerName==null)),我知道了,但我无法告诉您原因,因为我没有足够的答案回答我自己的问题。否则我得再等7个小时。。。谢谢你的帮助!它发生在字符串myPlayerNameSo上,然后c
必须为null
。通过添加的信息,这意味着Jail(客户端c)
的调用方正在传入null
。