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

Java入门开发问题:实现命令行参数字符串中高频数字的统计与升序输出

Hey there! Let's work through your problem step by step since you're just starting out with Java—no Map or fancy libraries needed, we'll keep it simple with basic arrays and loops.

First, Let's Fix Your Core Issues

Your original code had two main problems:

  • Unordered numbers: You added numbers to the ArrayList in the order they appeared in the string, so they didn't come out sorted.
  • Incorrectly including numbers with lower counts: When a new number with the same count as the current max was found, you added it—but if a later number had a higher count, you never removed the old ones (like the 4 in your 4th test case, which actually had fewer occurrences than 2).

A Simpler Approach (No Maps, Just Basic Arrays!)

Since we're only dealing with digits 0-9, we can use a fixed-size array of length 10 (index 0 = count of '0', index 1 = count of '1', ..., index 9 = count of '9'). This is perfect for beginners because it's straightforward, efficient, and automatically handles duplicates and sorting.

Here's the corrected code with detailed comments:

import java.util.ArrayList;

public class DigitCounter {
    public static void main(String[] args) {
        // Step 1: Combine command line arguments into a single string
        String input = "";
        if (args.length > 0) {
            StringBuilder sb = new StringBuilder(); // More efficient than repeated string concatenation!
            for (String arg : args) {
                sb.append(arg).append(" ");
            }
            input = sb.toString().trim(); // Trim to remove the extra trailing space
        }

        // Step 2: Count occurrences of each digit (0-9)
        int[] digitCounts = new int[10]; // Index 0 = count of '0', index 1 = count of '1', etc.
        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (Character.isDigit(c)) {
                // Convert char digit to its integer equivalent (e.g., '3' -> 3)
                int digit = c - '0';
                digitCounts[digit]++;
            }
        }

        // Step 3: Find the maximum occurrence count
        int maxCount = 0;
        for (int count : digitCounts) {
            if (count > maxCount) {
                maxCount = count;
            }
        }

        // Step 4: Collect all digits that have the max count (already in ascending order!)
        ArrayList<Integer> topDigits = new ArrayList<>();
        for (int i = 0; i < digitCounts.length; i++) {
            if (digitCounts[i] == maxCount && maxCount > 0) {
                topDigits.add(i);
            }
        }

        // Step 5: Output the results
        if (maxCount == 0) {
            System.out.println("The string '" + input + "' has no numbers.");
        } else {
            System.out.print("'" + input + "' -> ");
            for (int i = 0; i < topDigits.size(); i++) {
                System.out.print(topDigits.get(i));
                if (i != topDigits.size() - 1) {
                    System.out.print(" "); // Add space between digits, no trailing space
                }
            }
            System.out.printf(" (%d)\n", maxCount);
        }
    }
}

Let's Break Down Why This Works

  1. String Building: I used StringBuilder instead of repeated s = s + args[i] because string concatenation creates new objects every time, which is inefficient. StringBuilder is better for building strings in loops.
  2. Digit Counting Array: The digitCounts array lets us count each digit in one pass of the input string. No nested loops needed (your original code had nested loops which made it slower!).
  3. Finding Max Count: We loop through the digitCounts array once to find the highest number of occurrences.
  4. Collecting Top Digits: By looping from 0 to 9, we automatically collect digits in ascending order—no need to sort later!
  5. Clean Output: We handle the trailing space issue and edge case where there are no digits.

Testing Your Cases

Let's verify your test scenarios:

  1. Input: +386 40 253 987 → Output: '+386 40 253 987' -> 3 8 (2) ✅
  2. Input: hdch44 fg1t525 j6s99 → Output: 'hdch44 fg1t525 j6s99' -> 4 5 9 (2) ✅
  3. Input: d8d 82 a1810y51 → Output: 'd8d 82 a1810y51' -> 1 8 (3) ✅ (now sorted correctly!)
  4. Input: Your long text with numbers → Output: '[your long string]' -> 2 (9) ✅ (correctly excludes 4!)

Why Your Original Code Failed the 4th Test Case

In your first code, when you found 2 (count 9), you added it to the list. The problem was that you never reset the list when a higher count was found (though in this case, 2 was the highest). Wait, actually, the real issue was that you were checking digits multiple times—every time you encountered a 4, you counted its occurrences, but since you didn't track which digits you'd already checked, you might have added it to the list incorrectly if an earlier max count was lower. The array approach fixes this because we only collect digits that match the final, highest count.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 16:09:05