Hello once again! I need to make a program that will count the number of vowels and consonants in a string and have that number returned. The program runs, however, it always returns vowels or consonants as both being "null".
I am working off a UML and have the code essentially done, I just need to know why it is not returning a value. I have my code below, as well as the UML as an attachment. Maybe I am misinterpreting the UML? Or, more likely, something is screwed up in the countVowelsAndCons method?
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package vowelcons; import java.util.Scanner; /** * * @author Matthew Wood */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { String input; char selection; Scanner keyboard = new Scanner(System.in); System.out.println("Enter a string: "); input = keyboard.nextLine(); VowelCons vc = new VowelCons(input); do{ selection = getMenuSelection(); switch(Character.toLowerCase(selection)){ case 'a': System.out.println("\nNumber of vowels: " + vc.getNumVowels()); break; case 'b': System.out.println("\nNumber of consonants: " + vc.getNumConsonants()); break; case 'c': System.out.println("\nNumber of vowels: " + vc.getNumVowels()); System.out.println("\nNumber of consonants: " + vc.getNumConsonants()); break; case 'd': System.out.println("Enter a string: "); input = keyboard.nextLine(); vc = new VowelCons(input); } }while(Character.toLowerCase(selection) != 'e'); } public static char getMenuSelection(){ String input; char selection; Scanner keyboard = new Scanner(System.in); System.out.println("a) Count the number of vowels in the string."); System.out.println("b) Count the number of consonants in the string."); System.out.println("c) Count both the vowels and consonants in the string."); System.out.println("d) Enter another string."); System.out.println("e) Exit the program."); input = keyboard.nextLine(); selection = input.charAt(0); while(Character.toLowerCase(selection) < 'a' || Character.toLowerCase(selection) > 'e'){ System.out.println("Only enter a,b,c,d, or e: "); input = keyboard.nextLine(); selection = input.charAt(0); } return selection; } }
public class VowelCons { private char [] vowels; private char [] consonants; private int numVowels = 0; private int numCons = 0; private String str; public VowelCons(String string){ string = str; } public char[] getNumConsonants() { return consonants; } public char[] getNumVowels() { return vowels; } private void countVowelsAndConsonants(){ for (int i = 0; i < 100; i++) { char ch = str.charAt(i); if ((ch == 'a') || (ch == 'e') || (ch == 'i') || (ch == 'o') || (ch == 'u') ) { numVowels++; } else if (Character.isLetter(ch)) { numCons++; } } } }
Thanks for any help! It is greatly appreciated!