Once a value is stored as a String, how can you loop through string and assign each value to a char array? The occurrences of every vowel in array must also be counted.
This is my current code:
public class Part1_5 {
/**
* Method that gets user name and stores it as a string. Each value then
* assign to a char array. no of vowels are counted and no of each printed
*/
public static void main(String[] args) {
// Setting up scanner
Scanner scanner = new Scanner(System.in);
// declaring string for name
String userName = null;
// declaring ints to hold total no of each vowel
int totalOfA = 0;
int totalOfE = 0;
int totalofI = 0;
int totalofO = 0;
int totalofU = 0;
// Get user input for name
System.out.println("Please enter your Name...");
userName = scanner.nextLine();
for (int loop = 0; loop < userName.length(); loop++) {
// declaring char array
char[] letter = userName.toCharArray();
if (userName.charAt(0) == 'a') {
totalOfA++;
}
}
System.out.println(totalOfA);
}
}
char[] letter = userName.toCharArray();and replaceif (userName.charAt(0) == 'a') {withif (userName.charAt(loop) == 'a') {as suggested by pobrelkey. Now you've gotta do the same (if-condition and counting withloopas the index) for the remaining vowels. Note that this current implementation only capturesa, and notA. You could fix this by writingif (userName.charAt(loop) == 'a' || userName.charAt(loop) == 'A') {. Again, this way isn't pretty. :)usernameto an array to count the vowels, when you can just useusername.charAt()to get the character values individually. And even if for some reason you did want to create an array ofcharfrom aString, you'd just callyourString.toCharArray(). On the other hand, if your professor is making you write unnecessary code just to show you know how to instantiate an array and address its elements, that's another matter...