如何计算文本文件中有多少男性和女性?

vktxenjb  于 2021-07-12  发布在  Java
关注(0)|答案(2)|浏览(288)

假设文件包含两列,第一列对应于女性,第二列对应于男性。txt文件可以包含多行。我基本上只需要一个文件中女性和男性的总数。文件设置为两列之间的空格。按enter键分隔行。例如:

1 1
3 4
5 6

这是我到目前为止在文件中读到的。我不确定输出为数组列表是否合适。

public static ArrayList<Integer> simCity(File f) throws FileNotFoundException {
    Scanner scanner = new Scanner(f);

    f = new File(String.valueOf(scanner));
    ArrayList<Integer> integers = new ArrayList<>();
    while (scanner.hasNext()) {
        if (scanner.hasNextInt()) {
            integers.add(scanner.nextInt());
        } else {
            scanner.next();
        }
    }
    return integers;
}
cngwdvgl

cngwdvgl1#

//Use a try with resources so that the scanner is closed on completion
 int maleCount = 0;
 int femaleCount = 0;
 try (Scanner scanner = new Scanner(f)) {

    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        //TODO Check line is not empty whitespace... A good way of doing this is to use StringUtils.isBlank() in Apache Commons
        if (line.length() == 0) {
              //What to do?
        }
        String[] parts = line.split(" ");
        if (parts.length != 2) {
             //What do you want to do with an invalid line? Skip it? End program?
        } else {
            //wrap in a try catch - what if parts[X] isn't a number?
            //Or check the string contains only digits before parsing using StringUtils.isNumeric() which is part of Apache Commons 
            femaleCount += Integer.parseInt(parts[0]);
            maleCount += Integer.parseInt(parts[1]);
        }
    }
}
//Use the counts

如果您在方法中有这个,您可以从apachecommons返回一个immutablepair中的计数(https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/tuple/immutablepair.html)

2vuwiymt

2vuwiymt2#

首先,我更喜欢退货 List 接口到 ArrayList 具体类型,第二次声明(并初始化)您的 List 两个整数值(分别代表女性和男性模拟市民)。使用 try-with-Resources 以避免内存泄漏 Scanner (或显式关闭)。读取文件中的每一行,在空白处拆分并解析两个int值。将它们添加到各自的运行总数中。归还 List . 比如,

public static List<Integer> simCity(File f) throws FileNotFoundException {
    // Start with a List of femaleCounts = 0, maleCounts = 0
    List<Integer> totals = new ArrayList<>(Arrays.asList(0, 0));
    try (Scanner scanner = new Scanner(f)) {
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            // Skip empty lines
            if (line.isEmpty()) {
                continue;
            }
            // Tokenize the line
            String[] tokens = line.split("\\s+");
            // Add the line count of females
            totals.set(0, Integer.parseInt(tokens[0]) + totals.get(0));
            // Add the line count of males
            totals.set(1, Integer.parseInt(tokens[1]) + totals.get(1));
        }
    }
    // Return the List of femaleCounts, maleCounts
    return totals;
}

也许,定义一个自定义计数器类型会更好。这样你就可以 female 以及 male 独立于任何 List ,并使代码更易于推理。它甚至可以包含解析和加法逻辑!例如,

class SimCounter {
    private int female;
    private int male;

    public SimCounter(int female, int male) {
        this.female = female;
        this.male = male;
    }

    public void add(SimCounter sc) {
        this.female += sc.female;
        this.male += sc.male;
    }

    public int getFemale() {
        return female;
    }

    public int getMale() {
        return male;
    }

    public String toString() {
        return String.format("%d %d", female, male);
    }

    public static SimCounter parse(String line) {
        String[] tokens = line.split("\\s+");
        return new SimCounter(Integer.parseInt(tokens[0]), 
                Integer.parseInt(tokens[1]));
    }
}

然后您的方法可以实现为

public static SimCounter simCity(File f) throws FileNotFoundException {
    SimCounter counter = new SimCounter(0, 0);
    try (Scanner scanner = new Scanner(f)) {
        while (scanner.hasNextLine()) {
            counter.add(SimCounter.parse(scanner.nextLine()));
        }
    }
    return counter;
}

相关问题