我试图让用户输入一个字符串,然后显示在用户输入字符串中找到的所有元音,这是我的代码,但它无法显示正确的结果。
如果用户输入:我很绝望
结果应该是字符串中的所有元音:i, e, e, a, e
import java.util.Scanner;
public class Lab7stringvowels {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner (System.in);
System.out.println ("Enter a string:");
String s = input.nextLine();
char [] sChars = s.toCharArray();
char[] vowels = {'a','e','i','o','u'};
for (int j = 0 ; j < sChars.length ; j ++ ) {
for (int i = 0; i < vowels.length ; i++ ) {
if ( sChars == vowels) {
System.out.print(vowels[i] + " ");
}
}
}
}
}
最佳答案
您不应直接比较数组来查找元音,而是必须将数组名称与 for 循环中的索引结合使用。
//Initialize your arrays
for (int j = 0 ; j < sChars.length ; j ++ ) {
for (int i = 0; i < vowels.length ; i++ ) {
if ( sChars[j] == vowels[i]) {
System.out.print(vowels[i]+ " ");
}
}
}
关于java如何显示用户输入字符串中的所有元音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27509010/