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

Java实现输入字符串元音字母提取功能问题求助

嘿,我来帮你搞定这个问题!你的代码思路是对的——遍历字符串每个字符然后筛选元音,但有两个小问题需要修正,还有几种更简洁的实现方式,我慢慢给你讲:

先说说你当前代码的问题

  1. word.charAt(whatsat) 返回的是**char基本数据类型**,基本类型不能调用equals()方法,得用==来比较单个字符。
  2. 目前只判断了小写的a,没覆盖其他元音(包括大小写的a/e/i/o/u)。

解决方案1:扩展判断条件(最直观的入门写法)

直接用||(逻辑或)把所有元音的大小写情况都列出来:

import java.util.Scanner;
class Main {
    public static void main(String[] args) {
        Scanner inp = new Scanner(System.in);
        System.out.print("In:");
        String word = inp.nextLine();
        
        // 遍历字符串的每个字符
        for(int idx = 0; idx < word.length(); idx++){
            char currentChar = word.charAt(idx);
            // 检查所有大小写的元音字母
            if (currentChar == 'a' || currentChar == 'A' 
                || currentChar == 'e' || currentChar == 'E' 
                || currentChar == 'i' || currentChar == 'I' 
                || currentChar == 'o' || currentChar == 'O' 
                || currentChar == 'u' || currentChar == 'U'){
                System.out.print(currentChar);
            }
        }
    }
}

解决方案2:用字符串包含判断(更简洁的写法)

把所有元音存到一个字符串里,用indexOf()判断当前字符是否在元音集合中:

import java.util.Scanner;
class Main {
    public static void main(String[] args) {
        Scanner inp = new Scanner(System.in);
        System.out.print("In:");
        String word = inp.nextLine();
        // 把所有元音(大小写)放到一个字符串里
        String vowels = "aeiouAEIOU";
        
        for(int idx = 0; idx < word.length(); idx++){
            char currentChar = word.charAt(idx);
            // indexOf返回-1表示字符不在字符串中,反之则是元音
            if (vowels.indexOf(currentChar) != -1){
                System.out.print(currentChar);
            }
        }
    }
}

解决方案3:正则表达式(一行搞定的进阶写法)

用正则替换掉所有非元音字符,直接得到结果:

import java.util.Scanner;
class Main {
    public static void main(String[] args) {
        Scanner inp = new Scanner(System.in);
        System.out.print("In:");
        String word = inp.nextLine();
        
        // [^aeiouAEIOU] 表示"不是这些字符的所有字符",替换为空就只剩元音了
        String vowelsOnly = word.replaceAll("[^aeiouAEIOU]", "");
        System.out.print(vowelsOnly);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:18:11