Counting Vowels and Consonants...

Hellos All,
I have the following
import java.util.Scanner;
public class r3
public static void main(String[] args)
//declare variables
String userInput, workString = "";
int stringLength;
int numberVowels = 0;
char userChoice;
Scanner keyboard = new Scanner(System.in);
char[] vowelArray = {'a', 'e', 'i', 'o', 'u'};
boolean enterAString;
System.out.println("Would you like to enter a string");
enterAString = keyboard.nextBoolean();
//user input
while(enterAString)
{//begin loop
System.out.println("please enter a string");
userInput = keyboard.nextLine();
userInput = userInput.toLowerCase();
stringLength = userInput.length();
for(int i = 0; i < stringLength; ++i)
if((int)userInput.charAt(i) >= 97 && (int)userInput.charAt(i) <=122)
workString = workString + userInput.charAt(i);
for(int i = 0; i < stringLength; ++i)
if(userInput.charAt(i) >= 'a' && userInput.charAt(i) <= 'z')
workString = workString + userInput.charAt(i);
System.out.println(workString);
System.out.println("Please select\n"
+"a for number of vowels\n"
+"b for number of consonents\n"
+"c for number of vowels and consonents\n"
+"d to enter another string\n"
+"e to exit\n");
userChoice = ((keyboard.nextLine()).toLowerCase()).charAt(0);
System.out.println(userChoice);
//determin number of vowels
for(int i = 0; i < workString.length(); ++i)
for(int j = 0; j < vowelArray.length; ++j)
if(workString.charAt(i) == vowelArray[j])
numberVowels++;
switch(userChoice)
case 'a':
System.out.println("The number of vowels is: " + numberVowels);
break;
case 'b':
System.out.println("The number of consonents is: " + (workString.length() - numberVowels));
break;
case 'c':
System.out.println("The number of vowels and consonents is: " + workString.length());
break;
case 'd':
break;
case 'e':
enterAString = false;
break;
default:
System.out.println("Invalid input. Goodby.");
}//end switch
}//end loop
System.out.println("Thanks for playing");
}//end main
}//end classSo far it somewhat works fine, but for the number of consonents when printed. The number printed out is not equal to the string input by the user. The bigger the string gets the bigger the difference in the amount of consonants.
any help would be appretiated thanks

you can do this very easily by using 2 replace alls.
String userInput = ...
String pureText = (userInput.toLowerCase()).replaceAll("[^a-z]", "");
String vowels = pureText.replaceAll("[^aeiou]", "");
int vowelCount = vowels.length();
int consonantCount = pureText.length() - vowelCount;

Similar Messages

  • Help Counting Vowels and Consonants using a class

    I'm currently working on a class project where I need take a user inputed string and count how many vowels and/or consonants are in the String at the user discretion. I have the main logic program working fine. However, the trouble I'm running into is how to take the string the user inputed and pass that data into the class method for counting.
    Here is the code for the program:
    package vowelsandconsonants;
    import java.util.Scanner;
    public class VowelConsCounter {
        public static void main(String[] args) {
            String input; //User input
            char selection; //Menu selection
            //Create a Scanner object for keyboard input.
            Scanner keyboard = new Scanner(System.in);
            //Get the string to start out with.
            System.out.print("Enter a string: ");
            input = keyboard.nextLine();
            //Create a VowelCons object.
            VowelCons vc = new VowelCons(input);
            do {
                // Display the menu and get the user's selection.
                selection = getMenuSelection();
                // Act on the selection
                switch (Character.toLowerCase(selection)) {
                    case 'a':
                        System.out.println("\nNumber of Vowels: " +
                                vc.getNumVowels());
                        break;
                    case 'b':
                        System.out.println("\nNumber of consonats: " +
                                vc.getNumConsonants());
                        break;
                    case 'c':
                        System.out.println("\nNumber of Vowels: " +
                                vc.getNumVowels());
                        System.out.println("Number of consonants: " +
                                vc.getNumConsonants());
                        break;
                    case 'd':
                        System.out.print("Enter a string: ");
                        input = keyboard.nextLine();
                        vc = new VowelCons(input);
            } while (Character.toLowerCase(selection) != 'e');
         * The getMenuSelection method displays the menu and gets the user's choice.
        public static char getMenuSelection() {
            String input;  //To hold keyboard input
            char selection;  // The user's selection
            //Create a Scanner object for keyboard input.
            Scanner keyboard = new Scanner(System.in);
            //Display the menu.
            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.");
            //Get the user's selection
            input = keyboard.nextLine();
            selection = input.charAt(0);
            //Validate the input
            while (Character.toLowerCase(selection) < 'a' ||
                    Character.toLowerCase(selection) > 'e') {
                System.out.print("Only enter a,b,c,d or e:");
                input = keyboard.nextLine();
                selection = input.charAt(0);
            return selection;
    class VowelCons {
        private char[] vowels;
        private char[] consonants;
        private int numVowels = 0;
        private int numCons = 0;
        public VowelCons(String str) {
        public int getNumVowels() {
            return numVowels;
        public int getNumConsonants() {
            return numCons;
        private void countVowelsAndCons() {
            for (int i = 0; i < total; i++) {
                char ch = inputString.charAt(i);
                if ((ch == 'a') || (ch == 'A') || (ch == 'e') || (ch == 'E') || (ch == 'i') || (ch == 'I') || (ch == 'o') || (ch == 'O') || (ch == 'u') || (ch == 'U')) {
                    numVowels++;
                } else if (Character.isLetter(ch)) {
                    numCons++;
    }The UML given to me by my instructor calls for the counting method to be private. Being that I'm not too familiar with Java syntax I did not know if that may cause a problem with passing the user's input into that method.

    Well the only compilers i get are due to the code:
    private void countVowelsAndCons() {
            for (int i = 0; i < total; i++) {
                char ch = inputString.charAt(i);
                if ((ch == 'a') || (ch == 'A') || (ch == 'e') || (ch == 'E') || (ch == 'i') || (ch == 'I') || (ch == 'o') || (ch == 'O') || (ch == 'u') || (ch == 'U')) {
                    numVowels++;
                } else if (Character.isLetter(ch)) {
                    numCons++;
        }However, that is due to the fact that i have no data for those variables to use. I'm pretty much stuck on how to get the string the user inputs into that method shown above so the code can perform the task of counting the vowels and consonants.
    If i comment out the code within that function the program compiles and will allow me to enter the string and use the options but since i can't figure out how to pass the input to the counting method the program returns 0 for everything.

  • Trouble Counting Vowels and Consonants

    Hey I am trying to create a GUI that has three text fields, one for typing letters into it, the other two counts the vowels and consonants. However, I can't get the code to properly spit out any numbers and whenever I type in letters I get an exception: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class GUI extends JFrame implements KeyListener {
         public int numberOfConsonents = 0;
         public int numberOfVowels = 0;
         public JTextField jtf1;
         public JTextField jtf2;
         public JTextField jtf3;
         public JLabel jl3;
         public JLabel jl2;
         public GUI(){
         JTextField jtf1;
         JTextField jtf2;
         JTextField jtf3;
         jtf1 = new JTextField(20);
         jtf1.addKeyListener(this);
         jtf2 = new JTextField(5);
         jtf3 = new JTextField(5);
         jl2 = new JLabel("Vowels");
         jl3 = new JLabel("Consonants");
         jtf2.setEditable(false);
         jtf3.setEditable(false);
         getContentPane().setLayout(new GridLayout(2,3));
         getContentPane().add(jtf1);
         getContentPane().add(jl2);
         getContentPane().add(jtf2);
         getContentPane().add(jl3);
         getContentPane().add(jtf3);
         public void keyPressed (KeyEvent ke){
              char c = ke.getKeyChar();
              if (Character.isLetter(c)){
                   c = Character.toLowerCase(c);
                   if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'){
                        numberOfVowels++;
                        jtf3.setText(""+numberOfVowels);
                   else{
                        numberOfConsonents++;
                        jtf2.setText(""+numberOfConsonents);
              validate();
    //      not used
         public void keyReleased (KeyEvent ke){
         // not used
         public void keyTyped (KeyEvent ke){
         public static void main(String args[]){
              GUI gui = new GUI();
              gui.pack();
              gui.setVisible(true);
              gui.setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    In your constructor, don't re-declare the JTextFields. Essentially...
         public GUI(){
         jtf1 = new JTextField(20);
         jtf1.addKeyListener(this);
         jtf2 = new JTextField(5);
         jtf3 = new JTextField(5);
         jl2 = new JLabel("Vowels");
         jl3 = new JLabel("Consonants");
         jtf2.setEditable(false);
         jtf3.setEditable(false);
         getContentPane().setLayout(new GridLayout(2,3));
         getContentPane().add(jtf1);
         getContentPane().add(jl2);
         getContentPane().add(jtf2);
         getContentPane().add(jl3);
         getContentPane().add(jtf3);
         }The reason it's making an error is because you never construct the GLOBAL JTextFields. To access a JTextField globally, if you already have a JTextField with the same name in some method, you have to use this.theNameOfTheThing .

  • Vowels and consonants count of a string

    Hi...
    1.    plz provide code for counting no of  vowels and        Consonants   in a STRING.... suppose the string is BUSINESS.
    and also other
    2.     program to pass the string during runtime and couting vowels,consonants and also checking whether the string is palindrom or not.
    plz send me the code asap...
    Regards
    Narin.

    Hi,
       DATA :  v_string(40) VALUE  'BUSINESS',
                  v_cnt1 TYPE I,
                  v_cnt2 TYPE I VALUE 1,
                  v_len TYPE I,
                  v_num(10),
                  v_diff TYPE I,
                  v_vowels TYPE I ,
                 v_conso TYPE I.
    START-OF-SELECTION.
      v_len =  strlen( v_string ).
       DO v_len TIMES.
         IF v_string+v_cnt1(v_cnt2)  CA  'A,E,I,O,U'.
            v_vowels =  v_vowels  + 1.
         ELSE.
          v_conso =  v_conso + 1.
         ENDIF.
           v_cnt1 =  v_cnt1 + 1.
       ENDDO.
      WRITE : v_vowels  , v_conso.

  • How can i compare in percentage, vowels and consonants in english and german language?

    how can i compare in percentage, vowels and consonants in english and german language?

    Hi,
    Try comparing the Unicode value of the characters, see the code samples in these threads:
    Generating unicode
    for arabic character similar to Character map in c#
    How
    do you get the numeric unicode value of a  character?
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Pl/sql block to count no of vowels and consonents in a given string

    hi,
    I need a pl/sql block to count no of vowels and consonants in a given string.
    Program should prompt user to enter string and should print no of vowels and consonants in the given string.
    Regards
    Krishna

    Edit, correction to my above post which was wrong
    SQL> ed
    Wrote file afiedt.buf
      1  with t as (select '&required_string' as txt from dual)
      2  --
      3  select length(regexp_replace(txt,'([bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ])|.','\1')) as cons_count
      4        ,length(regexp_replace(txt,'([aeiouAEIOU])|.','\1')) as vowel_count
      5* from t
    SQL> /
    Enter value for required_string: This is my text string with vowels and consonants
    old   1: with t as (select '&required_string' as txt from dual)
    new   1: with t as (select 'This is my text string with vowels and consonants' as txt from dual)
    CONS_COUNT VOWEL_COUNT
            30          11
    SQL>

  • Counting vowels question

    Have the user input a sentence. Count the vowels and output your findings. Vowels are comprised of the letters: a e i o u. Remember that a vowel can be in upper case or lower case. (e.g., A or a)
    Your program could look as follows:
    im very confused..

    What is your question?  It looks almost as if you are submitting school assignments for people to solve for you here.
    If you are looking for an idea of how to code this, one way would be to create an array that contains the vowels and loop thru the sentence (String) and test each character to see if it is in the array (use the Array.indexOf() method).  Keep a count of how many match what is in the array.

  • How to get count,index and compare to arraylists

    hi
    how to get count,index and comparing of 2 arraylist.... plz suggest me asap...

    How is your question related to JDBC? And what have you done so far with your code?

  • Counting even and odd values

    Is there another way to count even and odd number than this one
    private static int countEvenOrOdd(int[] array, boolean countEvenNumbers){
              int count = 0;
              int remainderRequired = (countEvenNumbers ? 0 : 1);
              for(int i = 0; i < array.length; ++i){
                   if(array[i] % 2 == remainderRequired){
                        ++count;
              return count;
         }

    > I like hacking ;-) Have a look at this: ...
    Jos, you forgot the method for counting both:int countOddsAndEvens(int[] array) {
    return (countOdds(array) + countEvens(array));
    } ; )Yep, you're right, and for completeness reason I'd like to add the following:int countOthers(int[] array) {
       return array.length-countOddsAndEvens(array);
    }And for those junit maniacs:boolean testCounters(int[] array) {
       return countOddsAndEvens(array)+countOthers(array) == array.length;
    }btw, the moment I posted my previous reply I realized that I could've done better:int countOdds(int[] array) {
       int c= 0;
       for (int i= 0; i < array.length; c+= array[i++]&1);
       return c;
    }kind regards,
    Jos ( <-- never has to maintain others' code ;-)

  • What is the name of that thing that appears before a film, in black and white, with numbers counting backwards and with circle motion ?

    what is the name of that thing that appears before a film, in black and white, with numbers counting backwards and with circle motion ?

    Thanks a lot, not only I got what I needed, but also discovered a great site
    thanks
    fp

  • COUNTING RECORDS AND DETERMINING AVERAGES IN REPORT WRITER

    I HAVE 10 GROUPS. I WANT TO BE ABLE TO COUNT RECORDS AND DETERMINE THE AVERAGE DAYS FOR EACH GROUP. I GET DAYS BY SUBTRACTING THE RECEIVED DATE FROM THE RESULT DATE. I WANT TO DETERMINE THE AVERAGE DAYS AND THE NUMBER OF RECORDS IN THE TOP 10%, THE TOP 20%, THE TOP 30%, THE TOP 40%, THE TOP 50%, THE TOP 60%, THE TOP 70%, THE TOP 80%, THE TOP 90%, AND THE TOP 100%. HOW DO I CODE MY LOOP IN PLSQL TO DO THIS? CAN I DO THIS IN REPORT WRITER?

    I am not sure about the exact thing that you are requiring. but you can get the top 100 and top 20 or top 300 etc. by using the ROWNUM function in sql statement.
    thanks

  • Parsing (COunting Elements and Attributes)

    Can anyone point me to the method sfor counting elements and attributes in a parsed XML document. For example, I have a XML document that contains a number of 'word' files, I need to produce a printout that gives the total number. The files have a size attribute and I need to calculate and printout the total size of all the files together

    ChuckBing,
    Thanks for the pointers. I now have the following method:
    }  public void startElement(String elementName, AttributeList al) throws SAXException
          String attributeValue;
          if (elementName.equals("PRICE"))
          if(al.getLength()>0)
          for(int j = 0;j<al.getLength();j++)
            attributeValue = al.getValue(j);
            System.out.println("Total Attribute value is " + attributeValue);
          }This obviously allows me to extract the detail from "PRICE" but "PRICE" actually has two attributes. I can't find another method that allows me to extract out the detail for a specific attribute.
    Can you suggest anything?

  • An app counting minutes and data use. Please help!!!

    An app counting minutes and data use. Please help!!!

    Here's one, there are others in the App store:
    http://itunes.apple.com/us/app/data-usage/id386950560?mt=8
    However, since your carrier is the one that bills you, the only stats that matter are your carrier's. Some carrier's offer apps that provide this info, see if yours does.

  • Battery finishes in 2h 20 min maximum. Cycle count 375 and condition is normal. what to do please help????

    Battery finishes in 2h 20 min maximum. Cycle count 375 and condition is normal. what to do please help????

    No i have checked thorougly i dont have any window emulation parallel. i had a problem with my charger some days back that Apple replaced me. but after that i started having battery timing 2h 20 min maximum. the details about the MBP are as:
    MacBookPro6,2
    Charge Information:
      Charge remaining (mAh):          2375
      Fully charged:          No
      Charging:          No
      Full charge capacity (mAh):          6046
      Health Information:
      Cycle count:          376
      Condition:          Normal
      Battery Installed:          Yes
      Amperage (mA):          -1569
      Voltage (mV):          11043
                                     and (eww) i have read the related article linked http://support.apple.com/kb/TS1473 . though I could not understand the 5th point of this article but i think there is no problem about that.. PLEASE HELP

  • Differenct between count(0), count(1) and count(*)...???

    Hi,
    Please clarify the difference b/w count(0), count(1) and count(*)...???.
    SQL> set timing on
    SQL> select count(0) from trade
    2 /
    COUNT(0)
    112158506
    Elapsed: 00:00:03.08
    SQL> ed
    Wrote file afiedt.buf
    1* select count(1) from trade
    SQL> /
    COUNT(1)
    112158506
    Elapsed: 00:00:02.01
    SQL> ed
    Wrote file afiedt.buf
    1* select count(*) from trade
    SQL> /
    COUNT(*)
    112158506
    Elapsed: 00:00:02.03
    SQL>
    Is there any differences??
    Thanks
    SATHYA

    Looks the same to me
    admin@10gR2> create table big_table as select * from all_objects;
    Table created.
    admin@10gR2> set autotrace traceonly
    admin@10gR2> alter system flush shared_pool
      2  /
    System altered.
    admin@10gR2> select count(1) from big_table;
    Execution Plan
    Plan hash value: 599409829
    | Id  | Operation          | Name      | Rows  | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT   |           |     1 |   185   (2)| 00:00:03 |
    |   1 |  SORT AGGREGATE    |           |     1 |            |          |
    |   2 |   TABLE ACCESS FULL| BIG_TABLE | 72970 |   185   (2)| 00:00:03 |
    Note
       - dynamic sampling used for this statement
    Statistics
            322  recursive calls
              0  db block gets
            947  consistent gets
              0  physical reads
              0  redo size
            413  bytes sent via SQL*Net to client
            381  bytes received via SQL*Net from client
              2  SQL*Net roundtrips to/from client
              4  sorts (memory)
              0  sorts (disk)
              1  rows processed
    admin@10gR2> alter system flush shared_pool
      2  /
    System altered.
    admin@10gR2> select count(*) from big_table;
    Execution Plan
    Plan hash value: 599409829
    | Id  | Operation          | Name      | Rows  | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT   |           |     1 |   185   (2)| 00:00:03 |
    |   1 |  SORT AGGREGATE    |           |     1 |            |          |
    |   2 |   TABLE ACCESS FULL| BIG_TABLE | 72970 |   185   (2)| 00:00:03 |
    Note
       - dynamic sampling used for this statement
    Statistics
            322  recursive calls
              0  db block gets
            947  consistent gets
              0  physical reads
              0  redo size
            413  bytes sent via SQL*Net to client
            381  bytes received via SQL*Net from client
              2  SQL*Net roundtrips to/from client
              4  sorts (memory)
              0  sorts (disk)
              1  rows processed

Maybe you are looking for

  • Problem with BAPI of Material Master creation

    Hi, I am creating material master(mm01) through BAPI_MATERIAL_SAVEDATA. Program is working fine but when i m checking in MM03 to display uploaded data through BAPI, i cant able to see material which i created to through BAPI but i can see in MARA tab

  • Can't download SD version of HD movie

    I bought The Avengers in HD.  I want to download it to my 3rd Gen iPod Touch (so I need the SD version).  I know I have done this in the past.  I am using iTunes 11 and when I go to download the movie on the iPod Touch, instead of the cloud icon I se

  • Doubt in external table.

    I want to read the csv file and load into oracle table.But I am getting file with filename_<today date> for every day. Is it possible to use single External table to read file in dynamic. or what is the best way to do this? My oracle version 10g in w

  • Syncing Iphone with windows 7 calandar

    I've tried MobileMe but did not purchase the subscription. Is there anyway to sync the Iphone 3GS with the calendar program for Windows 7. If not what other calendar program is compatible with Windows 7?

  • Extract pages in same PDF version as original document

    That's it! It is annoying to extract pages from a PDF 1.3 doc. and have the resulting files be in PDF 1.6. It is also somewhat strange that the format is not even the native 1.7 format from Acrobat 8.1.1, which I'm using... The most useful implementa