java - 在java中从文本文档填充两个数组

标签 java arrays search netbeans search-engine

我想从文本文档中获取单词,然后在字符串数组中搜索它。如果该单词存在,那么我将在另一个整数数组中增加它的值,如果不存在,我将把它添加到字符串数组中,并在整数数组中增加它的值。

在代码末尾我必须有两个数组。一个字符串,其中包含该文档的单词,以及一个整数数组,该数组包含每个单词在所使用的文档中重复的次数。
但我的代码给了我一个空指针异常。为什么?

   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/

相关文章:

algorithm - 考虑到这些要求,最合适的数据结构是什么?

java - 我如何读取和解释 Java 程序中的/proc/acpi/battery/*?

java - 从网络应用程序发送短信

php - 对高度动态社交网站的基于 PHP 的搜索引擎的建议和偏好?

oracle - 使用Oracle Text的相关性

javascript - 比较 JavaScript 数组

java - 在 Java 程序中加载表

java - 有人可以告诉我为什么我的生命游戏代码不起作用吗?

javascript - 当使用 ".push"从数组生成数组时,我怎样才能更好地 "randomize"我的结果并控制重复项?

c - 指针符号