繁体   English   中英

并行阵列和文件读取

[英]Parallel Arrays and reading from a file

我需要帮助制作一个并行数组,我需要从字符串的文本文件中读取并创建一个字符串数组,该字符串数组将每个名称添加一次,并在整数数组中增加重复的字符串.....关于如何解决此问题的任何想法代码来做到这一点?

    Scanner sc=new Scanner(new File("Cat.txt"));
    String category=sc.nextLine();
    int total=sc.nextInt();
    int[]totcat=new int[total];
    String[]names=new String[total];
    while(sc.hasNextLine())
    {
        String x=sc.nextLine();
        boolean b=false;
        int size=0;
        for(int i=0;i<names.length;i++)
        {
            if(x.equals(names[i]))
            {
                b=true;
                totcat[i]++;
            }
        }
        if(!b)
        {
            names[size]=x;
            totcat[p]++;
            size;
        }
    }

问题是if(names[j].equals(null)) 这永远不会评估为true ,因为要做到这一点, names[j]必须为null ,因此它将抛出NullPointerException 正确的写法是if(names[j] == null)

一种更优雅的方法是使用另一个变量来跟踪数组中有多少个字符串,这样,如果找不到重复的字符串(您的if(!b)块),则只需添加字符串即可在由size变量指示的索引处,而不需要遍历整个数组以寻找null空间。

听起来您需要读取带有以换行符分隔的字符串的文件,并且最终要获得文件中找到的所有字符串的集合以及文件中每个字符串出现的次数的计数。

建议不要使用基于数组的结构,而建议使用Map。 在阅读源文件中的每一行时,您会检查映射以查看字符串值是否已存在于映射中。 如果是这样,则增加其值(一个int值),否则,将String添加到Map中。

像这样:

Map<String, Integer> map = new HashMap<>();

try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
  String line;
  while ((line = reader.readLine()) != null) {
    if(map.containsKey(line)) {
      Integer lineCount = map.get(line);
      map.put(line, lineCount++);
    } else {
      map.put(line, 1);
    }
  }
} catch(IOException ioe) {
  // Handle exception
}

这里需要注意的是内存限制。 如果您正在读取的文件很大和/或Java堆栈大小很小,则可能会遇到OutOfMemoryExceptions。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM