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

Java元音计数器优化咨询:如何用简洁方式替代多else if分支

嗨,作为Java新手能想着优化代码真的很棒!你的需求是单独统计每个元音的数量,确实不用写一堆else if分支,这里有几个更简洁的方案供你参考,顺便还能优化一些小细节:

先提个小优化点:你原来用word.substring(i, i + 1)获取单个字符,其实用word.charAt(i)直接返回char类型会更高效——不用额外创建字符串对象,性能更好哦。


方案1:使用HashMap(灵活易扩展)

这种方法适合以后可能要增加更多统计字符的场景,代码没有冗余的条件判断,扩展性拉满:

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        // 初始化元音与对应计数,默认都是0
        Map<Character, Integer> vowelCounts = new HashMap<>();
        vowelCounts.put('a', 0);
        vowelCounts.put('e', 0);
        vowelCounts.put('i', 0);
        vowelCounts.put('o', 0);
        vowelCounts.put('u', 0);

        System.out.print("Type a single word > ");
        String word = input.next().toLowerCase(); // 统一转小写,避免重复判断大小写

        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            // 如果是元音,直接更新计数
            if (vowelCounts.containsKey(c)) {
                vowelCounts.put(c, vowelCounts.get(c) + 1);
            }
        }

        // 输出统计结果
        int total = 0;
        System.out.println("\n'" + word + "' has...");
        for (Map.Entry<Character, Integer> entry : vowelCounts.entrySet()) {
            char vowel = Character.toUpperCase(entry.getKey());
            int count = entry.getValue();
            System.out.println(count + " " + vowel + "'s");
            total += count;
        }
        System.out.println("Total vowels: " + total + "\n");

        input.close();
    }
}

核心思路:用Map存储元音和计数的对应关系,循环时只需要判断当前字符是否在Map的key中,不用写一堆条件分支,后续要加其他字符直接往Map里加就行。


方案2:使用数组(性能最优)

因为元音数量固定是5个,我们可以把元音和数组索引绑定,数组的访问速度是最快的,适合追求性能的场景:

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int[] vowelCounts = new int[5]; // 索引对应顺序:A,E,I,O,U
        char[] lowerVowels = {'a', 'e', 'i', 'o', 'u'};
        char[] upperVowels = {'A', 'E', 'I', 'O', 'U'};

        System.out.print("Type a single word > ");
        String word = input.next().toLowerCase();

        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            // 找到当前字符对应的元音索引,更新计数
            for (int j = 0; j < lowerVowels.length; j++) {
                if (c == lowerVowels[j]) {
                    vowelCounts[j]++;
                    break;
                }
            }
        }

        // 输出结果
        int total = 0;
        System.out.println("\n'" + word + "' has...");
        for (int i = 0; i < vowelCounts.length; i++) {
            System.out.println(vowelCounts[i] + " " + upperVowels[i] + "'s");
            total += vowelCounts[i];
        }
        System.out.println("Total vowels: " + total + "\n");

        input.close();
    }
}

核心思路:用数组下标对应每个元音,通过内层循环匹配字符对应的索引,直接操作数组计数,性能比Map更好。


方案3:使用switch语句(简单直观)

如果你觉得Map和数组有点复杂,用switch替代else if也能让代码结构更清晰:

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int A = 0, E = 0, I = 0, O = 0, U = 0;

        System.out.print("Type a single word > ");
        String word = input.next();

        for (int i = 0; i < word.length(); i++) {
            char c = Character.toLowerCase(word.charAt(i));
            switch (c) {
                case 'a': A++; break;
                case 'e': E++; break;
                case 'i': I++; break;
                case 'o': O++; break;
                case 'u': U++; break;
                default: // 非元音,跳过
            }
        }

        int total = A + E + I + O + U;
        System.out.println("\n'" + word + "' has...\n" + A + " A's\n" + E + " E's\n" + I + " I's\n" + O + " O's\n" + U + " U's\nTotal vowels: " + total + "\n");
        input.close();
    }
}

核心思路:把字符转成小写后用switch匹配,每个case对应一个元音,比一串else if看起来整齐很多,逻辑也更直观。


总结一下:如果以后要扩展统计的字符,选Map;追求最高性能选数组;想要简单易上手,switch就很合适。你的原始代码其实也能正常工作,但这些优化方案能让代码更简洁、易维护,作为Java新手能主动思考优化真的值得鼓励!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 09:17:52