You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何统计自定义文本文件中每月日期记录数?求Java代码指导

Solution to Monthly Record Counting

Hey Dave, I see what you're trying to do here—let's get your monthly record count working properly. The main issues with your current code are that you aren't actually tracking counts per month, and you've got that skip logic we need to remove. Here's how to fix it step by step:

Key Fixes & Approach

  1. Add a counter array: We'll create an integer array that matches the order of your month names to track how many records fall into each month.
  2. Remove the skip logic: Since you want to ignore the if(col[2].equals("3") || col[2].equals("4")) check, we'll delete that block entirely to count all records.
  3. Extract and count months: For each line, pull the month abbreviation from the date field, find its position in your month list, and increment the corresponding counter.

Full Modified Code

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ContractSummary {
    public static void displaySummaryofContracts() { 
        int totalLines = 0; 
        String filePath = "test.txt"; 
        String[] monthNames = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
        int[] monthCounts = new int[monthNames.length]; // Starts with all zeros

        try (BufferedReader bufr = new BufferedReader(new FileReader(filePath))){ 
            String lineText = null; 
            while ((lineText = bufr.readLine()) != null){ 
                String[] col = lineText.split("\t"); 
                totalLines++;

                // Extract month from the first column's date string
                String[] dateParts = col[0].split("-");
                if (dateParts.length >= 2) { // Guard against malformed date lines
                    String currentMonth = dateParts[1];
                    // Match the month to our list and increment the count
                    for (int i = 0; i < monthNames.length; i++) {
                        if (monthNames[i].equals(currentMonth)) {
                            monthCounts[i]++;
                            break;
                        }
                    }
                }
            } 
        } catch (IOException | ArrayIndexOutOfBoundsException ioex){ 
            System.err.println("Error processing file: " + ioex.getMessage()); 
        } 

        System.out.println("Total Number of Lines: " + totalLines); 
        System.out.println("Number of dates connected to each month:");
        
        // Print month names in order
        for (String month : monthNames) {
            System.out.print(month + " ");
        }
        System.out.println();
        
        // Print corresponding counts (matches month order)
        for (int count : monthCounts) {
            System.out.print(count + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        displaySummaryofContracts();
    }
}

What This Code Does

  • Month Tracking: The monthCounts array aligns perfectly with your monthNames array—index 0 tracks January, index 1 tracks February, etc.
  • Date Parsing: Splits the first column (e.g., 03-Jan-2018) by - to grab the middle value, which is the month abbreviation.
  • Robustness: Includes a check to skip malformed date lines, so your code won't crash if a line has an unexpected format.
  • Clean Output: First prints all month names, then prints the counts directly below them in the same order, just like you requested.

内容的提问来源于stack exchange,提问作者Dave

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:02:06