Reputation: 65
I'm trying to use a for loop to examine each character in an array and print the character, it's position in the array, and what type of character it is (vowel, consonant, etc.). I have this so far:
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.");
}
How do I print the location of the character (i.e. "The character x located at position x is a vowel.")
Upvotes: 1
Views: 1474
Reputation: 425083
You're on the right track. Your loop is OK, but try the foreach
syntax if you don't actually need the index, like this:
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);
}
Now add in some logic:
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);
}
}
You must figure out what you want to do here. Now go do it :)
EDITED: To show use of position, which is a little clumsy, but still less code than a standard for loop
Upvotes: 3
Reputation: 4122
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++)
char c = myname[index];
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
{
System.out.println("The character " + c + "located at position " + index + " is a vowel.");
}
... }
Upvotes: 0
Reputation: 718986
Hints:
You should use the kind of for
loop that you are currently using. The value index variable is going to be useful in your output.
The Character class has a number of methods for classifying characters, and for converting from upper case to lower case & vice versa.
You can also use ==
to test characters ...
You could also use a switch statement to discriminate between the different kinds of letter, and use the default
branch for the rest.
Upvotes: 0