Sam_Cameron
Sam_Cameron

Reputation: 105

Check if char is a vowel using switch-case

I'm trying to check if each character in a string using switch a statement inside a while loop. So far I have this:

//f and g - vowel and consonant count
        int f, g, ind;
        f = 0;
        g = 0;
        ind = 0;
        char letter = sentence.charAt(ind);
        
        while (letter != sentence.charAt(ind)) {
            switch (letter) {
                case 'a', 'e', 'i', 'o', 'u', 'y', 'A', 'E', 'I', 'O', 'U', 'Y':
                    f += 1;
                    ind += 1;
                    break;
                    
                //in case it's a number, the code will pass to the next char
                case 1, 2, 3, 4, 5, 6, 7, 8, 9:
                    ind += 1;
                    break;
                 
                //in case it's a special character, the code will pass to the next char
                case '`', '~', '!', '@', '#', '$', '%', '^', '&', '*', '-', '_', '+', '=', '\\', '|', ';', ':', ',', '.', '/', '?':
                    ind += 1;
                    break;
                    
                default:
                    g += 1;
                    ind += 1;
                    break;
                    
            }
        }

For some reason it just returns 0 for both variables. Any suggestions? I'm to this btw so don't be too mean (a little bit is fine if I did something dumb). Also, if anyone has a more efficient way to check if the char is a special character, that would be much appreciated. Thanks in advance.

Upvotes: 1

Views: 1010

Answers (1)

0009laH
0009laH

Reputation: 1998

The variable letter never changes, so you always test the same character. Your while loop will stop when it reaches the first character that is different from the first one, so it will stop soon.

By the way, you may lighten your code calling consonants directly:

int f = 0, g = 0; // vowel and consonant counters
int ind = 0; // character index

while (ind < sentence.length()) {
    char letter = sentence.charAt(ind);
    switch (letter) {
        case 'a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U', 'y', 'Y':
            f += 1;
            break;

        case 'b', 'B', 'c', 'C', 'd', 'D', 'f', 'F', 'g', 'G', 'h', 'H', 
             'j', 'J', 'k', 'K', 'l', 'L', 'm', 'M', 'n', 'N', 'p', 'P', 
             'q', 'Q', 'r', 'R', 's', 'S', 't', 'T', 'v', 'V', 'w', 'W', 
             'x', 'X', 'z', 'Z':
            g += 1;
            break;
                
        default:
            break;
    }

    ind += 1;
}

Upvotes: 1

Related Questions