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

Java实现统计电话号码奇偶数字个数的问题求助

解决方案

核心思路

电话号码是字符串类型(且可能超出int取值范围),所以直接遍历字符串的每个字符,转成数字后判断奇偶,再根据传入的参数统计对应类型的数字个数,最后输出指定格式的结果。

完整实现代码

public class DigitCounter {
    // 统计指定号码中偶数/奇数数字的个数,并输出结果
    static void countDigits(String phoneNumber, String type) {
        int count = 0;
        // 遍历电话号码的每个字符
        for (char c : phoneNumber.toCharArray()) {
            // 将字符转换为数字
            int digit = c - '0';
            // 根据类型判断是否计数
            if ("even".equalsIgnoreCase(type)) {
                if (digit % 2 == 0) count++;
            } else if ("odd".equalsIgnoreCase(type)) {
                if (digit % 2 != 0) count++;
            } else {
                System.out.println("Invalid type! Please use 'even' or 'odd'");
                return;
            }
        }
        // 输出指定格式的结果
        System.out.printf("i have %d %s digits in %s%n", count, type, phoneNumber);
    }

    public static void main(String[] args) {
        String telUDM = "5143436111";
        String telJean = "4501897654";
        
        // 调用函数统计并输出
        countDigits(telUDM, "odd");
        countDigits(telJean, "even");
    }
}

代码说明

  • 字符串遍历:用toCharArray()拆分电话号码字符串,逐个处理每个字符。
  • 字符转数字:通过c - '0'将字符形式的数字转为整数,简单高效。
  • 参数兼容:用equalsIgnoreCase()处理参数,避免大小写敏感问题(比如传入"Even"也能正常识别)。
  • 格式输出:用printf()简化指定格式的字符串输出,代码更简洁。

运行结果

i have 7 odd digits in 5143436111
i have 5 even digits in 4501897654

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 03:01:00