Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 12 of 12

Thread: Returning Null

  1. #1
    Junior Member
    Join Date
    Jul 2010
    Posts
    10
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Returning Null

    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!
    Attached Images Attached Images


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Returning Null

    Where do you ever assign any values to the returned variables?

  3. #3
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Returning Null

    Norm is sending you in the right direction, so I have a question. Should we treating "Y" as a vowel or a consonant?

  4. #4
    Junior Member
    Join Date
    Jul 2010
    Posts
    10
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Returning Null

    @aussie - "Y" is treated as a consonant.

    @Norm - Are you asking if I initialized the return variables to any value? Or is that I need to assign a variable to my return variables? I'm sorry, I am just a little bit confused by the question.

  5. #5
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Returning Null

    Ok, he is saying that in the following code:

    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++;
                }
        }
     
        }
    }

    The variables you are returning are char [] vowels by the getNumVowels() method and char [] consonants by the getNumConsonants() method, correct?

    Well, where do you actually initialize char [] vowels and char [] consonants?

    At the moment, you do not. So, these variables have no value. Because they have no value, when you say to return them, null is returned.

    As well as that, you have initialized str incorrectly in the constructor.
    By saying:
    public VowelCons(String string){
                string = str;
        }
    You are saying, set string equal to str. You want to do the opposite. So you want to say this:
    public VowelCons(String string){
                str = string;
        }
    Remember that the variable on the left of the equals sign is the variable being set and variable on the right of the equals sign is the value you are giving the variable on the left. With the setup you had, you are setting string to be equal to str. At the time, str is null because it wasnt given a value. However, since the variable string is being immediately garbage collected due to scope, it is not causing your Null value.

    What you have done is you have given numVowels and numCons their appropriate values, but you do not use them to construct the char arrays.

    I dont know how you plan on doing this specifically, but an array is constructed in two ways (that I know of):

    1.
    String[] array;
    array = new String[]{ "A","B","C","D"};

    2.
    String[] array;
    array = new String[4];
    array[0] = "A";
    array[1] = "B";
    array[2] = "C";
    array[3] = "D";

    Both of these methods will construct the exact same arrays, but the different methods of constructing them are appropriate in different circumstances.
    Last edited by aussiemcgr; July 21st, 2010 at 09:25 PM.

  6. The Following 2 Users Say Thank You to aussiemcgr For This Useful Post:

    JavaPF (July 22nd, 2010), Woody619 (July 21st, 2010)

  7. #6
    Junior Member
    Join Date
    Jul 2010
    Posts
    10
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Returning Null

    Thanks for that push from both of you! However, when I do give the array values, I get something like this "[C@13caecd" returned instead of the number of vowels or consonants! Any thoughts to where I may be going wrong?

    I took out the values of the array for the sake of brevity, but the returned result is the same.

    public char[] getNumConsonants() {
            consonants = new char[]{};
            return consonants;
        }
     
        public char[] getNumVowels() {
            vowels = new char[]{};
            return vowels;
        }

    Also if I try to declare the array in the method I get an error message. This is what I did before taking it out, just to show that I am following you.

    public char[] getNumConsonants() {
            char[] = consonants;
            consonants = new char[]{};
            return consonants;
        }

  8. #7
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Returning Null

    Arrays do not have a good default toString() method. So, the data is in there, but you must access it individually.

    char[] myString = new char[]{'h','e','l','l','o'};
    System.out.println("myString: " + myString); // pretty much just garbage
    for(int i = 0; i < myString.length; i++)
    {
        System.out.println(myString[i]); // print out each element separately
    }
    Last edited by helloworld922; July 21st, 2010 at 10:32 PM.

  9. #8
    Junior Member
    Join Date
    Jul 2010
    Posts
    10
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Returning Null

    @helloworld922 -- Wouldn't that array just return a string letter as opposed to a number (which is what is needed) ? It is supposed to return the number of vowels/consonants in a string.

  10. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Returning Null

    Arrays are a little tricky. They are a kind of object. You can define an array without putting any values into it.
    char[] anArray = new char[10]; // create an array with 10 slots. All ten slots will be null

    anArray[0] = 'c'; // put a value into the array. now the first element has a value.

    When you print an array variable, what do expect to see? Its an object with some contents. The default toString() method returns something like: "[C@13caecd" which says [= an array, C= char, @... the address in memory.

    To see the contents of the array you either need to specifically index each element in it or you could use the Arrays.toString() method.

  11. #10
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Returning Null

    Repeat after me:

    Java is not C/C++

    In java, Strings are a separate entity from char arrays (however, the underlying implementation of String most likely uses a char array).

    So, in C/C++, there is an end-of-string character (Java does have this character, but it doesn't serve the same purpose, Java uses the string Length to determine how many characters there are). Printing out a "string" was basically print out each character one-by-one until you reach the terminator character.

    When you print out a string in Java, the underlying implementation is actually doing something similar to what I have above because the length is known before-hand.
    Last edited by helloworld922; July 22nd, 2010 at 12:11 PM.

  12. #11
    Member Darryl.Burke's Avatar
    Join Date
    Mar 2010
    Location
    Madgaon, Goa, India
    Posts
    494
    Thanks
    8
    Thanked 48 Times in 46 Posts

    Default Re: Returning Null

    Quote Originally Posted by Norm View Post
    char[] anArray = new char[10]; // create an array with 10 slots. All ten slots will be null
    No, they'll have the value '\0'

    Primitives can't be null.

    db

  13. #12
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Returning Null

    Hmm, learn something new every day.

Similar Threads

  1. url input stream returning blank
    By yo99 in forum File I/O & Other I/O Streams
    Replies: 7
    Last Post: June 2nd, 2010, 08:14 PM
  2. returning a 2D array
    By straw in forum What's Wrong With My Code?
    Replies: 3
    Last Post: March 11th, 2010, 04:30 AM
  3. Arrays.equals not returning correct answer.
    By Anyone in forum Collections and Generics
    Replies: 2
    Last Post: February 11th, 2010, 10:12 AM
  4. throwing and returning
    By chronoz13 in forum Exceptions
    Replies: 6
    Last Post: October 25th, 2009, 12:00 AM
  5. Returning Random Strings from an Array
    By cfmonster in forum Collections and Generics
    Replies: 3
    Last Post: September 8th, 2009, 11:13 PM