我想从文本文档中获取单词,然后在字符串数组中搜索它。如果该单词存在,那么我将在另一个整数数组中增加它的值,如果不存在,我将把它添加到字符串数组中,并在整数数组中增加它的值。
在代码末尾我必须有两个数组。一个字符串,其中包含该文档的单词,以及一个整数数组,该数组包含每个单词在所使用的文档中重复的次数。
但我的代码给了我一个空指针异常。为什么?
try{
FileReader reader = new FileReader("C:\\Users\\name\\Desktop\\IRP\\finalstemmer\\Algorithm.stp");
FileReader reader2 = new FileReader("C:\\Users\\name\\Desktop\\IRP\\finalstemmer\\Algorithm.stp");
BufferedReader bufferedReader = new BufferedReader(reader);
BufferedReader bufferedReader2 = new BufferedReader(reader2);
String word ,word2 , newWord;
int n =0;
while ((word = bufferedReader.readLine()) != null) {
n++;}
System.out.println(n);
String [] anArray = new String[n];
int [] count = new int[n];
while ((word2 = bufferedReader2.readLine()) != null) {
for (int k = 0; k < word2.split(" ").length; k++) {
newWord = word2.split(" ")[k];
int i = 0;
while(!anArray[i].equalsIgnoreCase(newWord)){
if(anArray[i].equals(null))
break;
i++;
}
if(anArray[i].equals(null)){
anArray[i]=newWord;
count[i]++;
}else
if(anArray[i].equals(newWord)){
count[i]++;
}
}
}
System.out.println(Arrays.toString(anArray));
System.out.println(Arrays.toString(count));
}catch (Exception e) {
System.out.println(e);
} // TODO code applicat
有人可以帮忙吗?
最佳答案
您可以通过使用 HashSet 非常有效地做到这一点。 如果可以成功添加该单词,则该单词在 HashSet 中不存在。 HashSet 包含唯一的元素。根据这个,只需增加你的计数器数组,它应该保存单词明智的计数器
这里有一个示例代码来解释基本策略
public static void main(String[] args)
{
String sal[]={"val","sa","de","dal","val","sa","de"}; // just an example array of word
HashSet<String> ss = new HashSet(Arrays.asList(sal)); // any Hash set containing String Element
System.out.println("HashSet-");
System.out.println(ss);
if(ss.add("vald")){ // word does not exists
System.out.println("Not exist");
// Do your code here
}else{
//word exist just increase the array couter
}
}
o/p:
HashSet-
[de, val, sa, dal]
Not exist
关于java - 在java中从文本文档填充两个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49909245/