Greg Smith
Greg Smith

Reputation: 67

String to char issue

I am trying to write a simple program that counts the amount of vowels, consonants, and spaces in a string that is user inputed. I'm having an issue with my do while loop and if statements. It counts everything as a space instead of a vowel or consonant. Please let me know if you guys have any suggestions! :)

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import javax.swing.JOptionPane;

public class VowelCounter {

private static final Set<String> 
        vowels = new HashSet<>
        (Arrays.asList("a","e","i","o","u","y"));

private static final Set<String> 
        cons = new HashSet<>
        (Arrays.asList("b","c","d","f","g","h","j","k","l","m","n","p","q","r","s","t","v","w","x","z"));

public static void main(String[] args) {

    // ---------------------------------------------- VARIABLE DECLARATIONS
    int vnum = 0;
    int snum = 0;
    int cnum = 0;
    int i = 0;


    // -------------------------------------------------------------- INPUT
    String input = JOptionPane.showInputDialog
        ("Enter name (like your university)");
    // --------------------------------------------------------- PROCESSING
    char result = input.charAt(i);

    do{
        if (vowels.contains(result))
            vnum++;

        if (cons.contains(result))
            cnum++;

        if (!input.matches(("[a-zA-Z]+")))
            snum++; 


        i++;
    }while (i < input.length());

    System.out.println("There are " + vnum + " vowels, " + cnum + " consonants, and " + snum + "spaces");

Upvotes: 0

Views: 125

Answers (2)

shmosel
shmosel

Reputation: 50716

  1. You're not going to find a char in a Set<String>.

  2. In your loop, you're incrementing i but not selecting the the corresponding character.

  3. You're unnecessarily (and incorrectly) using regex where a simple else will suffice.

Try this:

private static final Set<Character> 
        vowels = new HashSet<>
        (Arrays.asList('a','e','i','o','u','y'));

private static final Set<Character> 
        cons = new HashSet<>
        (Arrays.asList('b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','z'));

...

    for (int i = 0; i < input.length(); i++) {
        Character result = input.charAt(i);
        if (vowels.contains(result))
            vnum++;
        else if (cons.contains(result))
            cnum++;
        else
            snum++;
    }

Upvotes: 1

FredK
FredK

Reputation: 4084

Your loop never modifies result, so it is always the first character input.

Upvotes: 0

Related Questions