Reputation: 67
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
Reputation: 50716
You're not going to find a char
in a Set<String>
.
In your loop, you're incrementing i
but not selecting the the corresponding character.
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
Reputation: 4084
Your loop never modifies result
, so it is always the first character input.
Upvotes: 0