[英]Error: java.lang.NullPointerException
I'm trying to code a text analysis program, and one of the methods is supposed to write a file containing every word started by a certain letter and the number of occurences of that word, using a text file as input ( BufferedReader
and whatnot). 我正在尝试编写一个文本分析程序,其中一个方法应该写一个文件,其中包含由某个字母开始的每个单词以及该单词的出现次数,使用文本文件作为输入(
BufferedReader
和whatnot) 。
If input is: "O Pai Natal nao existe. Mas o coelho da Pascoa existe (ea Fada dos Dentes tambem)." 如果输入是:“O Pai Natal nao existe.Mas o coelho da Pascoa existe(ea Fada dos Dentes tambem)。”
Output for e should be: EXISTE 2E 1 My code so far is as follows – I know I could have used a HashMap
, but this is school work and we haven't learned that yet, so I'm trying to keep it within what was lectured –: e的输出应该是:EXISTE 2E 1我的代码到目前为止如下 - 我知道我可以使用
HashMap
,但这是学校工作,我们还没有学到这一点,所以我试图把它保持在什么讲课 - :
void WordList(char c, String file) throws IOException {
BufferedWriter out = new BufferedWriter(new FileWriter(ficheiro+".txt"));
String[] words = null;
int indexVector = 0;
String[] wordAlreadyWritten = null;
int indexVector2 = 0;
for (int i = 0; i < text.length; i++) {
if (text[i].charAt(0) == c) {
words[indexVector] = texto[i]; /*error here */
indexVector++;
}
}
for (int i = 0; i < words.length; i++) { /*error here*/
if (!wordWasAlreadyWritten(words[i], wordAlreadyWritten)) {
out.write(words[i] + ": " + countNumberRepetitions(words[i], words));
wordAlreadyWritten[indexVector2] = words[i]; /* error here*/
indexVector2++;
}
}
out.close();
}
I am also using some auxiliary methods as some may have noticed: 有些人可能已经注意到我也在使用一些辅助方法:
static boolean wordWasAlreadyWritten(String original, String[] array) {
boolean was = false;
for (int j = 0; j < array.length; j++) {
if (original.equals(array[j])) {
was = true;
}
}
return was;
}
static int countNumberRepetitions(String word, String[] array) {
int counter = 1;
for (int i = 0; i < array.length; i++) {
if (word.equals(array[i])) {
contador++;
}
}
return counter;
}
If someone can explain the java.lang.NullPointerException
I'm getting and how to fix it, I would be very thankful. 如果有人能解释我正在获取的
java.lang.NullPointerException
以及如何修复它,我会非常感激。 Also if someone has any idea on how to make my code better, it would also be greatly appreciated. 此外,如果有人知道如何使我的代码更好,也将非常感激。
Initial both the String array 初始化String数组
String[] words = new String[count]; // count any integer value
String[] wordAlreadyWritten = new String[count]; // count any integer value
Due to which you are facing error. 因此您将面临错误。
Few Q's: 几个Q:
Another suggestion: 另一个建议是:
You haven't studied HashMap but still you can write your own HashMap like implementation or closely resemble to that. 你还没有研究过HashMap,但你仍然可以编写自己喜欢的HashMap,或者与它非常相似。 I am sure you will learn something out of it.
我相信你会从中学到一些东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.