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.

Similar Messages

  • 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 .

  • 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;

  • 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.

  • 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.

  • 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.

  • ALV like LIST GRID BLOCKED and HIRARCHIC using oops class SALV

    Hi ,
    Can any one let know me is it possible to display all the Flavours of ALV like LIST GRID BLOCKED and HIRARCHICAL
    using oops class CL_GUI_ALV and class CL_SALV.
    and the relevant events with respect to the type of ALV.
    regards

    Hello
    Have you had a look at the documents of Rich Heilman:
    [ALV Object Model - Simple 2D Table - Event Handling|https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/cda3992d-0e01-0010-90b2-c4e1f899ac01]
    [ALV Object Model - Hierarchical Sequential List - The Basics|https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/b0f03986-046c-2910-a5aa-e5364e96ea2c]
    [ALV Object Model - Simple 2D Table - The Basics|https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/eac1fa0b-0e01-0010-0990-8530de4908a6]
    Regards
      Uwe

  • Customizing FD01 and FB70 using PS Class and Characteristics

    Hello SAP Experts
    I have the following issue:
    My client has a requirement where we need to customize the Customer Master  (FD01) screen and the Invoice Posting Screen (FB70). A few additional fields have to be added by creating a separate tab. I was intending to take Abaper's help and do this using user exits but I have been suggested by the cleint to use SAP PS Class and Characteristics feature to do this. Can someone please throw some light on this feature and how can i create custom fields on FD01 and FB70 screens. Is there a way we could customize these screens using PS class and characteristics. Your opinions would be much appreciated.
    Please kindly give your suggestions. Thanks in advance
    Regards,
    Nik

    Joao Paulo,
    Thank you for the response. I have tried to obtain some info from OSS but no luck. Tried all means but there is limited information available.
    Nik

  • Need help to read and write using UTF-16LE

    Hello,
    I am in need of yr help.
    In my application i am using UTF-16LE to export and import the data when i am doing immediate.
    And sometimes i need to do the import in an scheduled formate..i.e the export and imort will happend in the specified time.
    But in my application when i am doing scheduled import, they used the URL class to build the URL for that file and copy the data to one temp file to do the event later.
    The importing file is in UTF-16LE formate and i need to write the code for that encoding formate.
    The problem is when i am doing scheduled import i need to copy the data of the file into one temp place and they doing the import.
    When copying the data from one file to the temp i cant use the UTF-16LE encoding into the URL .And if i get the path from the URl and creating the reader and writer its giving the FileNotFound exception.
    Here is the excisting code,
    protected void copyFile(String rootURL, String fileName) {
    URL url = null;
    try {
    url = new URL(rootURL);
    } catch(java.net.MalformedURLException ex) {
    if(url != null) {
    BufferedWriter out = null;
    BufferedReader in = null;
    try {
    out = new BufferedWriter(new FileWriter(fileName));
    in = new BufferedReader(new InputStreamReader(url.openStream()));
    String line;
    do {
    line = in.readLine();
    if(line != null) {
    out.write(line, 0, line.length());
    out.newLine();
    } while(line != null);
    in.close();
    out.close();
    } catch(Exception ex) {
    Here String rootURL is the real file name from where i have to get the data and its UTF-16LE formate.And String fileName is the tem filename and it logical one.
    I think i tried to describe the problem.
    Plz anyone help me.
    Thanks in advance.

    Hello,
    thanks for yr reply...
    I did the as per yr words using StreamWriter but the problem is i need a temp file name to create writer to write into that.
    but its an logical one and its not in real so if i create Streamwriten in that its through FileNotFound exception.
    The only problem is the existing code build using URL and i can change all the lines and its very difficult because its vast amount of data.
    Is anyother way to solve this issue?
    Once again thanks..

  • Problem in creating EJB and WebService using complex class structure

    Hi All,
    My requirement is like :
    I have a class with very complex structure.
    I have also used external .jars.
    Now when I have created an EJB with a method's return parameter as above class.
    But when I am creating a Webservice, it doesnot allow me to select this method.
    Not able to configure why ?
    Please Help.
    Thanks.

    Hi,
    I have gone through your code and the problem is that when you create jar it takes a complete path address (which is called using getAbsolutePath ) (when you extract you see the path; C:\..\...\..\ )
    You need to truncate this complete path and take only the path address where your files are stored and the problem must be solved.

  • Help with menus and variables in different classes.

    1) how do I change variables in different classes? My situation..
    I have a few tabbed panels/planes, that ask for different user inputs. I want the last tabbed panel/plane to have the inputs on 1 plane. Is that confusing?
    Code:
            JTabbedPane tp = new JTabbedPane();
            tp.addTab ("Kitchen", new KitchenPanel());
            tp.addTab ("Living Room", new LivingRoomPanel());
            tp.addTab ("Master Bedroom", new MasterBedPanel());
            tp.addTab ("Bedroom 1", new Bedroom1Panel());
            tp.addTab ("Bedroom 2", new Bedroom2Panel());
            tp.addTab ("Misc Use", new MiscPanel());
            tp.addTab ("Totals", new TotalsPanel());not the full thing obviously, but just so u see what im working with.
    2) How do popup menus work? I have a menu (File -> About | File -> How to Contact)
    I want The File->About menu item, to prompt a dialog
    The File -> How to to prompt a dialog
    Contact Menu(Not Item) to load a webpage
    thanks again for the help, and i hope its not to confusing
    Edited by: 2point2ek on May 25, 2009 9:51 PM

    It's better to think in terms of transferring data between object, rather than between classes.
    What you need is for the tab pane objects to have a reference to some common object to which the data is to be sent. This common object might be the total pane. It's generally better design to keep the data in separate objects from the presentation (in this case the totals pane), but at this stage that's probably just going to confuse you.
    The simplest way to get this reference in is to the pane objects is as a constructor argument, which the constructor of your pane objects saves in a field. As you create each pane you pass it a reference and it stores that reference for when it needs to save data.
    Then, when you click detect the action by which the user tells the program to store the data he's entered the pane class should call a method on the central data object, passing all the data from that pane. If there's a lot of it, wrap it up in an object (typically called a "data transfer object").
    The central data object would be responsible for dealing with this data, amending totals etc.. It might delegate responsibility for updating the display to a separate total pane object.

  • Graphic card help for Pr and Ae use

    Hi there great community :)
    I'm currently working with only the on-board graphic card, and of course I should upgrade as my GPU is working on 99% on large renders and they are slow...
    I've been recommended the GeForce nvidia 2-4GB gtx 760, but neither the 750 or 760 are listed as supported graphic cards in the premiere cc system requirements.
    Is there a reason for this or should I ignore that?
    Is there a good reason for spending a little extra cash on the 4 GB vs the 2 GB card ?
    What exactly will a graphic card do for my performance? (I'm not a computer expert)
    My general use is premiere cc and after effects cc
    Hope you'll help. Greatly appreciated!
    Nice weekend to all :)
    - Simon

    Premiere accelerates both playback and export with the  GPU. AE Ray Tracer acceleration is far more limited and will only be used for a limited functions.
    Eric
    ADK

  • My sister and I use the same itunes library and account. My Ipod is registered to her. How do I register it to me? Please help., My sister and I use the same Itunes and Itunes account. My Ipod is registered to her. How do I register it to me? Please help.

    I registered my sister Ipod on my laptop through itunes, and i registered mine on it also. So now it says both ipod touch's are registered to her. I do i change that so mine can be registered to only me.

    What is saying that both are registered to her?

  • How to use global classes and display returned data?

    Hello experts,
    I have the following code in a program which accesses a global class (found in the class library). It executes one it's static methods. What I would like to do is to get hold of some elements of the returned data. How do I do that please?
    Your help is greatly appreciated.
    ***Use global class CL_ISU_CUSTOMER_CONTACT
    DATA: o_ref TYPE REF TO CL_ISU_CUSTOMER_CONTACT.
    DATA: dref_tab LIKE TABLE OF O_ref.
    DATA: begin OF o_ref2,
    CONTACTID               TYPE CT_CONTACT,
    P_INSTANCES             TYPE string,
    P_CONTEXT               TYPE CT_BPCCONF,
    P_CONTROL               TYPE ISU_OBJECT_CONTROL_DATA,
    P_DATA                  TYPE BCONTD,         "<<<=== THIS IS A STRUCTURE CONTAINING OTHER DATA ELEMENTS
    P_NOTICE                TYPE EENOT_NOTICE_AUTO,
    P_OBJECTS               TYPE BAPIBCONTACT_OBJECT_TAB,
    P_OBJECTS_WITH_ROLES    TYPE BAPIBCONTACT_OBJROLE_TAB,
    end of o_ref2.
    TRY.
        CALL METHOD CL_ISU_CUSTOMER_CONTACT=>SELECT  "<<<=== STATIC METHODE & PUBLIC VISIBILITY
          EXPORTING
           X_CONTACTID = '000001114875'   "Whatever value here
          RECEIVING
            Y_CONTACTLOG = o_ref
    ENDTRY.
    WHAT I WOULD LIKE TO DO IS TO MOVE o_ref TO o_ref2 and then display:
    1) P_DATA-PARTNER
    2) P_DATA-ALTPARTNER
    How can I do this please?

    I now have the following code. But when I check for syntax I get different error. They are at the end of the list.
    Here is the code the way it stands now:
    ================================================
    ***Use global class CL_ISU_CUSTOMER_CONTACT
    DATA: oref TYPE REF TO CL_ISU_CUSTOMER_CONTACT.
    DATA: dref_tab LIKE TABLE OF oref.
    DATA: begin OF oref2,
    CONTACTID TYPE CT_CONTACT,
    P_INSTANCES TYPE string,
    P_CONTEXT TYPE CT_BPCCONF,
    P_CONTROL TYPE ISU_OBJECT_CONTROL_DATA,
    P_DATA TYPE BCONTD,      "THIS IS A STRUCTURE CONTAINING OTHER DATA ELEMENTS
    P_NOTICE TYPE EENOT_NOTICE_AUTO,
    P_OBJECTS TYPE BAPIBCONTACT_OBJECT_TAB,
    P_OBJECTS_WITH_ROLES TYPE BAPIBCONTACT_OBJROLE_TAB,
    end of oref2.
    TRY.
    CALL METHOD CL_ISU_CUSTOMER_CONTACT=>SELECT     " STATIC METHODE & PUBLIC VISIBILITY
    EXPORTING
    X_CONTACTID = '000001114875' "Whatever value here
    RECEIVING
    Y_CONTACTLOG = oref
    ENDTRY.
    field-symbols: <FS1>      type any table,
                   <wa_oref2> type any.
    create data dref_tab type handle oref.   " <<===ERROR LINE
    assign dref->* to <FS1>.
    Loop at <FS1> assigning  <wa_oref2>.
    *use <wa_orfe2> to transfer into oref2.
    endloop.
    write: / 'hello'.
    =========================================
    Here are the errors I get:
    The field "DREF" is unknown, but there is a field with the similar name "OREF" . . . .
    When I replace itr by OREF I get:
    "OREF" is not a data reference variable.
    I then try to change it to dref_tab. I get:
    "DREF_TAB" is not a data reference variable.
    Any idea? By the way, must there be a HANDLE event for this to work?
    Thanks for your help.

  • 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>

Maybe you are looking for