Java实现输入字符串元音字母提取功能问题求助
嘿,我来帮你搞定这个问题!你的代码思路是对的——遍历字符串每个字符然后筛选元音,但有两个小问题需要修正,还有几种更简洁的实现方式,我慢慢给你讲:
先说说你当前代码的问题
word.charAt(whatsat)返回的是**char基本数据类型**,基本类型不能调用equals()方法,得用==来比较单个字符。- 目前只判断了小写的
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
相关产品推荐
相关产品推荐

