Adding only specific text from a file to an array list, part 2 - Java

前端 未结 2 884
名媛妹妹
名媛妹妹 2021-01-29 10:06

I hope I can have some great suggestion how I can solve this here:

I have this text file with places and names - name detail indicates the place(s) that the person has v

相关标签:
2条回答
  • 2021-01-29 10:39

    Instead of having a Name class, how about a Traveler class that has String name and List<Place> places? You could then have a method add(Place p) on the Traveler class.

    0 讨论(0)
  • 2021-01-29 11:00

    It might be better to use a regular expression to extract the digit on the line instead of trying to track/guess it (see below).

    This is a tested recreation of your code since you reference some classes that you didn't provide...but this should hopefully help:

    public static String getMatch(final String pattern, final String content) {
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(content);
    
        if (m.find()) {
            return m.group(1);
        } else {
            return "";
        }
    }
    
    public static void load(String fileName) throws FileNotFoundException {
    
        List<String> places = new ArrayList<String>();
        List<String> names = new ArrayList<String>();
        List<String> nameDetails = new ArrayList<String>();
    
        BufferedReader br = new BufferedReader(new FileReader(fileName));
    
        String text;
        String lastName = "";
    
        try {
    
            while ((text = br.readLine()) != null) {
                // extract num from start of line or empty if none..
                String num = getMatch("^([0-9]+)\\.", text);
    
                if (text.contains("Place:")) {
                    text = text.replaceAll("Place:", "");
                    places.add(text);
                } else if (text.contains(num + ". Name:")) {
                    text = text.replaceAll(num + ". Name:", "");
                    names.add(text);
                    lastName = text;
                } else if (text.contains(num + ". Name detail:")) {
                    text = text.replaceAll(num + ". Name detail:", "");
                    nameDetails.add(lastName + " had " + text);
                }
            }
        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
        }
    
        System.out.println("Places:" + places);
        System.out.println("Names:" + names);
        System.out.println("Name Details:" + nameDetails);
    }
    
    0 讨论(0)
提交回复
热议问题