【问题标题】:Filling two arrays from text document in java从java中的文本文档填充两个数组
【发布时间】:2018-04-18 21:25:49
【问题描述】:

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

在代码的最后,我必须有两个数组。包含该文档的单词的字符串和包含每个单词的整数数组,在使用的文档中重复了多少。
但是我的代码给了我一个空指针异常。为什么?

   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

有人可以帮忙吗?

【问题讨论】:

  • 你能发布你的整个代码和错误日志吗?
  • 这是我的全部代码
  • 你从哪里得到 NPE?
  • 对不起,不知道什么是NPE?我是java初学者..
  • 空指针异常

标签: java arrays search netbeans search-engine


【解决方案1】:

您可以通过非常有效地使用 HashSet 来做到这一点。 如果可以成功添加单词,则 HashSet 中不存在该单词。 HashSet 包含唯一元素。并据此增加你的计数器数组,它应该包含单词 wise counter

这是一个解释基本策略的示例代码

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

【讨论】:

    【解决方案2】:

    您应该使用== 来检查对象是否为空。

    所以if(yourObject == null) 是正确的方式。

    第二件事是字符串应该像这样拆分:

    word2.split("\\s+").length
    

    【讨论】:

      猜你喜欢
      • 2023-03-07
      • 1970-01-01
      • 2019-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-21
      • 2017-06-06
      • 1970-01-01
      相关资源
      最近更新 更多