分享
三行代码  ›  专栏  ›  技术社区  ›  neuroandstats

我怎样才能在一个文本文件中统计出有多少男性和女性?

  •  0
  • neuroandstats  · 技术社区  · 7 月前

    假设文件包含两列,第一列对应于雌性,第二列对应于雄性。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;
    }
    
    2 回复  |  直到 7 月前
        1
  •  1
  •   tomgeraghty3    7 月前
     //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 
    

    如果在一个方法中有这个,那么可以从Apache Commons返回不可变对中的计数( https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/tuple/ImmutablePair.html )

        2
  •  5
  •   Elliott Frisch    7 月前

    首先,希望返回 List ArrayList 具体类型,第二次声明(并初始化)您的 列表 两个整数值(分别代表女性和男性模拟人生)。使用 try-with-Resources Scanner (或者明确地关闭它)。读取文件中的每一行,将其拆分为空白并解析这两个int值。将它们添加到各自的运行总数中。返回 . 就像,

    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 列表

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