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

Java程序统计整数0位数:为何直接数字判断0失效?

问题解答

核心原因

问题出在:charAt(index)返回的是字符的ASCII编码值,不是数字本身。比如字符'0'对应的ASCII码是48,'1'是49,以此类推。所以当你把charAt的结果直接赋值给test时,test的值是48而不是0,自然test == 0永远不会成立。

解决方法:把字符转成对应数字

要直接用数字形式判断0,你需要把字符转换成对应的整数。方法很简单:用当前字符减去'0'的ASCII值——因为0-9的字符在ASCII表中是连续排列的,这样就能得到对应的0-9整数:

test = inputString.charAt(index) - '0';

修改后,test就会是你期望的数字值,此时if(test == 0)就能正常触发统计。

修正后的完整代码

另外原代码还有个逻辑小问题:原来的even会把0也统计进去(因为48是偶数),导致even的计数包含了zero的数量。用else if替代独立if就能避免重复统计:

import java.util.Scanner;

public class ParseInt {
    public static void main(String[] args) {
        
        //Declarations
        int index = 0, test, odd = 0, even = 0, zero = 0;
        String inputString;
        Scanner scan = new Scanner(System.in);
        
        //Inputs
        System.out.println("Input an integer");
        inputString = scan.nextLine();
        
        //Process
        while(index <= inputString.length()-1)
        {
            // 将字符转换为对应数字
            test = inputString.charAt(index) - '0';
            
            if(test == 0) 
                zero++;
            else if(test % 2 == 0)
                even++;
            else
                odd++;
            
            index++;
        }
        
        System.out.println("The number of zero digits is " + zero + ".");
        System.out.println("The number of even digits is " + even + ".");
        System.out.println("The number of odd digits is " + odd + ".");
        
        scan.close();
    }
}

补充说明

  • 字符转数字的原理:ASCII表中'0'的编码是48,'1'是49,直到'9'是57。所以'5' - '0'的结果就是5(53-48=5),以此类推,能快速把字符数字转成整数。
  • 用else if连锁判断,确保每个数字只会被统计到一个分类里,不会重复计数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 17:45:37