简体   繁体   中英

Parallel Arrays and reading from a file

I need help making a parallel array I need to read in from a textfile of strings and create a array of strings that adds each name once and increments repeated strings in an array of ints..... any ideas of how i can fix this code to do that?

    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;
        }
    }

The problem is the line if(names[j].equals(null)) . This will never evaluate to true , since for that to happen, names[j] would have to be null , and so it would instead throw a NullPointerException . The correct way to write it would be if(names[j] == null) .

A more elegant way would be to have another variable to keep track of how many strings you have in your array, so that if you don't find a repeated string (your if(!b) block), you can just add the string at the index indicated by the size variable, instead of having to go through the whole array looking for a null space.

It sounds like you need to read a file with Strings that are delimited by line breaks, and you want to end up with a set of all Strings found in the file as well as a count of the number of times each String occurs in the file.

Rather than trying to build an array-based structure, I'd recommend using a Map. As you read each line in the source file you check the map to see if the String value already exists in the map. If so, you increment it's value (an int), if not, you add the String to the Map.

Something like this:

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
}

Something to watch our for here is memory limitations. If the file you are reading is very large and/or your Java stack size is small, you may encounter OutOfMemoryExceptions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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