我正在尝试使用 for 循环来检查数组中的每个字符并打印该字符、它在数组中的位置以及它是什么类型的字符(元音、辅音等)。到目前为止我有这个:
char[] myName = new char[] {'J', 'o', 'h', 'n', ' ', 'D', 'o', 'e'};
System.out.print("\nMy name is: ");
for(int index=0; index < myName.length ; index++)
System.out.print(myName[index]);
for(char c : myName) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
{
System.out.println("The character located at position is a vowel.");
}
else if (c == 'j' || c == 'h' || c == 'n' || c == 'd')
{
System.out.println("The character located at position is a consonant.");
}
else if (c == ' ')
{
System.out.println("The character located at position is a space.");
}
如何打印字符的位置(即“位于 x 位置的字符 x 是元音字母。”)
最佳答案
您走在正确的轨道上。您的循环没问题,但如果您实际上不需要索引,请尝试使用 foreach
语法,如下所示:
char[] myName = new char[] {'J', 'o', 'h', 'n', ' ', 'D', 'o', 'e'};
System.out.print("\nMy name is: ");
for(char c : myName) {
System.out.print(c);
}
现在添加一些逻辑:
int i = 0;
for(char c : myName) {
i++;
// Is the char a vowel?
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
// do something - eg print in uppercase
System.out.print(Character.toUpperCase(c) + " at position " + i);
} else {
// do something else - eg print in lowercase
System.out.print(Character.toLowerCase(c) + " at position " + i);
}
}
你必须弄清楚你想在这里做什么。现在去做:)
已编辑:显示位置的使用,这有点笨拙,但仍然比标准的 for 循环代码少
关于java - 使用 for 循环检查数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6313846/