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

如何使用数组优化Java中冗长if-else结构的数字计数代码?

优化方案说明

数组不需要在while循环内创建,放在try代码块内、while循环外即可,你需要全局累计整个文件的数字出现次数,放在循环内会导致每次读取新行时计数被重置,不符合统计需求。

优化逻辑很简单:

  • 用长度为10的int数组counts替换原来的10个独立count变量,数组下标09刚好对应数字09的计数位
  • 删掉原来的10个char常量定义,利用ASCII码连续的特性,字符'0'到'9'的数值连续,数字字符c对应的数组下标直接用c - '0'计算即可
  • 原来的多层if-else判断可以直接简化为一步判断+数组下标计数

优化后完整代码

import java.io.FileReader;
import java.io.FileNotFoundException;
import java.util.Scanner;
    
public class Homework4A {

    public static void main(String[] args) throws FileNotFoundException {
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter name of the input file: ");
        String fileName = scan.next();
        try (Scanner inFile = new Scanner(new FileReader(fileName))) {
            // 长度10的数组存0-9的计数,int数组默认初始值全为0
            int[] counts = new int[10];
            
            while (inFile.hasNextLine()) {
                String line = inFile.nextLine();
                for (int i = 0; i < line.length(); i++) {
                    char c = line.charAt(i);
                    // 仅统计数字字符
                    if (c >= '0' && c <= '9') {
                        // 字符减'0'得到对应数字作为下标,计数加1
                        counts[c - '0']++;
                    }
                }
            }
            
            System.out.println("\n-= Count of Thistles in  =-");
            System.out.println("-= the Hundred Acre Wood =-\n");
            System.out.println("        -----------");
            System.out.println("        type  count");
            System.out.println("        -----------");
            // 循环输出结果,避免重复写10行打印代码
            for (int i = 0; i < counts.length; i++) {
                System.out.printf("         %d      %d%n", i, counts[i]);
            }
            System.out.println("        -----------");
        }

    }
    
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 17:15:06