
Originally Posted by
harold
This one I can't figure for the life of me--the program is supposed to prompt the user to input a sequence of characters and should output the number of vowels. For example, adsfoiu so, output is 4.
Not sure what I'm doing wrong??
public class VowelCount {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
char ch;
int counter = 0;
String str;
System.out.print("Enter a string of characters: ");
System.out.flush();
str = console.next();
System.out.println();
int len = str.length();
for(int i = 0; i <= (len - 1); i++) {
ch = console.next().charAt(0);
if (isVowel(ch) == true)
counter++;
console.next().charAt(0);
}
System.out.println("The number of vowels in the string is: " + counter);
}
public static boolean isVowel(char c) {
switch(c) {
case 'a': case 'e': case 'i': case 'o': case 'u':
case 'A': case 'E': case 'I': case 'O': case 'U':
return true;
}
return false;
}
}
These statements
Code:
ch = console.next().charAt(0);
console.next().charAt(0);
are not doing what you think. Replace the first with
Code:
ch = str.charAt(i);
and delete the second one.
Now to be able to debug your own programs, you need a way to check that the program is doing what you think it is doing. There are two ways to go:
- use a debugger to step through the program and show you the values of the variables and what functions are being executed, or
- put in print statements. For example, if you just printed out the value of ch within the loop, you would see it does not have the values you think. And if you printed out str, you'd see it does have the values you want.
Debuggers are good if you have one and know how to use it. Otherwise, start putting in print statements when you are puzzled by the behavior of a program.
And by the way, the need to be skilled in debugging programs does not go away with experience. The programs just get more complicated, the mistakes more subtle, and the need to be skilled in debugging increases.