I'm wondering if someone can help me figure out my getAverageLength method in the following code:

package com.abc.text;

public class StringProcessing {
    
    /**
     * Returns the number of non-null strings in the set.
     * If null or a zero-length array is passed in, then zero is returned.
     * If a slot in the array is null, then it is ignored (not counted).
     */  
    public static int getCount(String[] set) { 
        
        int stringCounter = 0;
        if (set == null || set.length == 0) {
            return 0;
        }
        else {
            for (int a = 0; a < set.length; a++) {
                if (set[a] == null) {
                    stringCounter += 0;
                }
                else {
                    stringCounter += 1;
                }
                
            }
            return stringCounter;
        }

        }
            
    /**
     * Returns the total length of all the non-null strings in the set.
     * If null or a zero-length array is passed in, then zero is returned.
     * If a slot in the array is null, then it is ignored (not counted).
     */
    public static int getTotalLength(String[] set) {
        
        int lengthCounter = 0;
        if (set == null || set.length == 0) {
            return 0;
        }
        else {
            for (int a = 0; a < set.length; a++) {
                if (set[a] == null) {
                    lengthCounter += 0;
                }
                else {
                    if (set[a] != null)
                    lengthCounter += set[a].length();
                }
                // return lengthCounter;  
            }
            return lengthCounter;
        }

        }
        //return -1;
    

    /**
     * Returns the average length of all the non-null strings in the set.
     * If null or a zero-length array is passed in, then zero is returned.
     * If a slot in the array is null, then it is ignored (not counted).
     */
    public static double getAverageLength(String[] set) {
        
        
        
        int averageLength = 0;
        if (set == null || set.length == 0 ) {
            return 0.0;
        }
        else {
            for (int a = 0; a < set.length; a++) {
                if (set[a] == null) {
                    averageLength += 0;
                }
                else {
                    if (set[a] != null) {
                        averageLength += set[a].length();
                        
                    }
                }
                double average =  averageLength / set.length;
                            
            }
        }
        return averageLength;
        // using count and length to get average, cast as double
        
    }

    /**
     * Returns the length of the shortest, non-null string in the set.
     * If null or a zero-length array is passed in, then zero is returned.
     * If a slot in the array is null, then it is ignored (not counted).
     */
    public static int getShortestLength(String[] set) {
       return 1;
    }

    /**
     * Returns the shortest, non-null string in the set (which was found first).
     * If two strings in the set are of the same length, then the first one
     * found is the one returned.
     * If null or a zero-length array is passed in, then null is returned.
     * If a slot in the array is null, then it is ignored (not counted).
     * If every slot in the array is null, then null is returned.
     */
    public static String getFirstShortest(String[] set) {
        return "First shortest goes here";
    }
    
    /**
     * Returns the length of the longest, non-null string in the set.
     * If null or a zero-length array is passed in, then zero is returned.
     * If a slot in the array is null, then it is ignored (not counted).
     */
    public static int getLongestLength(String[] set) {
        return 2;
    }

    /**
     * Returns the longest, non-null string in the set (which was found first).
     * If two strings in the set are of the same length, then the first one
     * found is the one returned.
     * If null or a zero-length array is passed in, then null is returned.
     * If a slot in the array is null, then it is ignored (not counted).
     * If every slot in the array is null, then null is returned.
     */
    public static String getFirstLongest(String[] set) { 
        return "First longest goes here";
    }    
   
    /**
     * Sorts the specified array by string length in ascending order.
     * Shorter strings come before longer strings.
     * Use your own code for bubble sort.
     * If null or a zero-length array is passed in, then nothing is done.
     * If a slot in the array is null, then it is considered to be longer
     * than any actual string (null's sort to be at the end).
     */     
    public static void sortLength(String[] list) {
        
        for ( int j = list.length - 1; j > 0; j-- ) {
            boolean swapped = false;
            for ( int i = 0; i < j; i++ ) {
                if ( list[i].length() > (list[i + 1]).length()) {
                    String tmp = list[i];
                    list[i] = list[i + 1];
                    list[i + 1] = tmp;
                    swapped = true;
                }
            }
            if (swapped == false) {
                break;
            }

        }
    }
    
    // this method is complete, do not alter it
    private static String format(String[] set) {
        if ( set == null ) {
            return "String[] is null";
        }
        StringBuilder sb = new StringBuilder();
        for ( int i = 0; i < set.length; i++ ) {
            if ( i > 0 ) {
                sb.append(", ");
            }
            sb.append(quoteWrap(set[i]));
        }
        return sb.toString();
    }
    
    // this method is complete, do not alter it
    private static String quoteWrap(String s) {
        if ( s == null ) {
            return "null";
        } else {
            return '"' + s + '"';
        }
    }

    // this method is complete, do not alter it
    private static void process(String[] set) {
        System.out.println("Original String[]: " + format(set));
        System.out.printf("  %3d   - count%n", getCount(set));
        System.out.printf("  %3d   - shortest length (%s)%n", 
            getShortestLength(set), quoteWrap(getFirstShortest(set)));
        System.out.printf("  %3d   - longest length (%s)%n", 
            getLongestLength(set), quoteWrap(getFirstLongest(set)));
        System.out.printf("  %5.1f - average length%n", getAverageLength(set)); 
        System.out.printf("  %3d   - total length%n", getTotalLength(set));
        sortLength(set);
        System.out.println("after length sort: " + format(set));
        System.out.println("----------");
    }
    
    // this method is complete, do not alter it
    public static void main(String[] args) {
        process(new String[] { "apple" });
        process(new String[] { "watermelon", "grape" });
        process(new String[] { "pear", "date" });
        process(new String[] { "cherry", "apple", "pear", "grape", "banana" });
        
        /*
        // Zero-length strings are OK, they just have a length of zero
        process(new String[] { "" });
        process(new String[] { "", "apple", "", "cherry", "banana" });
                
        // A zero-length array
        process(new String[0]);
        
        // No array at all, just null passed in
        process(null);
        
        // Some slots contain null instead of a String
        process(new String[] { null });
        process(new String[] { null, null });
        process(new String[] { null, "apple", null });
        process(new String[] { null, "", null });
        process(new String[] { null, "apple", null, "cherry", "banana" });
        */
        
    }
}

The output is providing me with the total length of the string array, the part I'm stuck on is having the loop divide total length by number of strings in each array. (Looking for assistance, not asking for final answer).

In calculating the average, you sum the elements and then divide by the number of elements. That would imply that division does not occur within the loop.

Revising that slightly: division shouldn't occur in the loop.

You have the answer right there in your code, you just need to alter the location of a single calculation and return that instead.

Revising that slightly: division shouldn't occur in the loop.

You have the answer right there in your code, you just need to alter the location of a single calculation and return that instead.

Thanks Ezzaral, that fixed my issue :)

I wonder if you could point me in the right direction for my next method? I'm currently working on my getShortestLength method...however, I've tried several different approaches and none have seemed to work. I need it to return the integer length of the shortest string in the arrays. Code posted below:

public static int getShortestLength(String[] set) {
      
        int shortestLength = 0;
        if (set == null || set.length == 0) {
            return 0;
        }
        else {
            for (int a = 0; a < set.length; a++) {
                if (set[a] == null) {
                    shortestLength += 0;
                }
                else {
                    if (set[a] != null) {
                        shortestLength += set[a].length();
                    }

                   // lengthCounter += set[a].length();
                  //  return set[a].length();
                }
                
                        
                    }
                }
            return shortestLength;
                // return lengthCounter;  
            }

Currently I am returning the length of the entire array...I'm just stuck on how to compare the lengths of strings in each array and return the shortest of them.

Consider the steps you would go through with a pencil to note the shortest or longest in a series of numbers. You need a place to keep the min/max that you have found so far. Then you simply start going through the list one by one. If you find one shorter/longer, you update your min/max.

Consider the steps you would go through with a pencil to note the shortest or longest in a series of numbers. You need a place to keep the min/max that you have found so far. Then you simply start going through the list one by one. If you find one shorter/longer, you update your min/max.

Thank you :icon_smile:. I've finished that method now as well... a lot of this stuff is trial and error for me since I'm just starting out in a fundamentals class. I've been studying my tail off the entire semester, but there are still a few "cloudy" areas that I can always use more explaining on.

Thanks for your help Ezzaral.

You're welcome. Glad you completed it.

You're welcome. Glad you completed it.

One more question for ya Ez (concerning:

// A zero-length array
        process(new String[0]);

)

My code looks like this now:

package com.abc.text;

public class StringProcessing {
    
    /**
     * Returns the number of non-null strings in the set.
     * If null or a zero-length array is passed in, then zero is returned.
     * If a slot in the array is null, then it is ignored (not counted).
     */  
    public static int getCount(String[] set) { 
        
        int stringCounter = 0;
        if (set.length == 0 || set == null) {
            return 0;
        }
        else {
            for (int a = 0; a < set.length; a++) {
                if (set[a] == null) {
                    stringCounter += 0;
                }
                else {
                    stringCounter += 1;
                }                
            }
            return stringCounter;
        }
    }
            
    /**
     * Returns the total length of all the non-null strings in the set.
     * If null or a zero-length array is passed in, then zero is returned.
     * If a slot in the array is null, then it is ignored (not counted).
     */
    public static int getTotalLength(String[] set) {        
        int lengthCounter = 0;
        if (set.length == 0 || set == null) {
            return 0;
        }
        else {
            for (int a = 0; a < set.length; a++) {
                if (set[a] == null) {
                    lengthCounter += 0;
                }
                else {
                    if (set[a] != null)
                    lengthCounter += set[a].length();
                }  
            }
            return lengthCounter;
        }
    }
    

    /**
     * Returns the average length of all the non-null strings in the set.
     * If null or a zero-length array is passed in, then zero is returned.
     * If a slot in the array is null, then it is ignored (not counted).
     */
    public static double getAverageLength(String[] set) {        
        int count = 0;
        int sum = set.length;
        
        if (set.length == 0 || set == null) {
            return 0.0;
        }
        else {
            for (int a = 0; a < set.length; a++) {
                if (set[a] == null) {
                    count += 0;
                }
                else {
                    if (set[a] != null) {
                        count += set[a].length();                       
                    }
                }       
            }
        }
        // using count and length to get average, cast as double
        double average =  (double) count / sum;
         return average;
    }

    /**
     * Returns the length of the shortest, non-null string in the set.
     * If null or a zero-length array is passed in, then zero is returned.
     * If a slot in the array is null, then it is ignored (not counted).
     */
    public static int getShortestLength(String[] set) {      
        int lengthCounter = 0;
        int minValue = set[0].length();

        if (set.length == 0 || set == null) {
            return 0;
        }
        else {
            for (int a = 1; a < set.length; a++) {
                if (set[a] == null) {
                    lengthCounter += 0;
                }
                else {
                    if (set[a] != null) {
                        if (set[a].length() < minValue) {
                            minValue = set[a].length();
                        }                        
                    }
                }

            }
        }
        return minValue;  
    }

        
        

    /**
     * Returns the shortest, non-null string in the set (which was found first).
     * If two strings in the set are of the same length, then the first one
     * found is the one returned.
     * If null or a zero-length array is passed in, then null is returned.
     * If a slot in the array is null, then it is ignored (not counted).
     * If every slot in the array is null, then null is returned.
     */
    public static String getFirstShortest(String[] set) {         
        int lengthCounter = 0;
        String minValue = set[0];

        if (set.length == 0 || set == null) {
            return "null";
        }
        else {
            for (int a = 1; a < set.length; a++) {
                if (set[a] == null) {
                    lengthCounter += 0;
                }
                else {
                    if (set[a] != null) {
                        lengthCounter += set[a].length();
                        if (set[a].length() < minValue.length()) {
                            minValue = set[a];
                        }                        
                    }
                }
            }
        }
        
        return minValue;
    }
    
    /**
     * Returns the length of the longest, non-null string in the set.
     * If null or a zero-length array is passed in, then zero is returned.
     * If a slot in the array is null, then it is ignored (not counted).
     */
    public static int getLongestLength(String[] set) {
        int lengthCounter = 0;
        int maxValue = set[0].length();

        if (set.length == 0 ||  set == null) {
            return 0;
        }
        else {
            for (int a = 1; a < set.length; a++) {
                if (set[a] == null) {
                    lengthCounter += 0;
                }
                else {
                    if (set[a] != null) {
                        if (set[a].length() > maxValue) {
                            maxValue = set[a].length();
                        }                        
                    }
                }
            }
        }
        return maxValue;
    }

    /**
     * Returns the longest, non-null string in the set (which was found first).
     * If two strings in the set are of the same length, then the first one
     * found is the one returned.
     * If null or a zero-length array is passed in, then null is returned.
     * If a slot in the array is null, then it is ignored (not counted).
     * If every slot in the array is null, then null is returned.
     */
    public static String getFirstLongest(String[] set) { 
        int lengthCounter = 0;
        String maxValue = set[0];

        if (set.length == 0 || set == null ) {
            return "null";
        }
        else {
            for (int a = 1; a < set.length; a++) {
                if (set[a] == null) {
                    lengthCounter += 0;
                }
                else {
                    if (set[a] != null) {
                        lengthCounter += set[a].length();
                        if (set[a].length() > maxValue.length()) {
                            maxValue = set[a];
                        }                        
                    }
                }
            }
        }
        
        return maxValue;
    }    
   
    /**
     * Sorts the specified array by string length in ascending order.
     * Shorter strings come before longer strings.
     * Use your own code for bubble sort.
     * If null or a zero-length array is passed in, then nothing is done.
     * If a slot in the array is null, then it is considered to be longer
     * than any actual string (null's sort to be at the end).
     */     
    public static void sortLength(String[] list) {         
        for ( int j = list.length - 1; j > 0; j-- ) {
            boolean swapped = false;
            for ( int i = 0; i < j; i++ ) {
                if ( list[i].length() > (list[i + 1]).length()) {
                    String tmp = list[i];
                    list[i] = list[i + 1];
                    list[i + 1] = tmp;
                    swapped = true;
                }
            }
            if (swapped == false) {
                break;
            }
        }
    }
    
    // this method is complete, do not alter it
    private static String format(String[] set) {
        if ( set == null ) {
            return "String[] is null";
        }
        StringBuilder sb = new StringBuilder();
        for ( int i = 0; i < set.length; i++ ) {
            if ( i > 0 ) {
                sb.append(", ");
            }
            sb.append(quoteWrap(set[i]));
        }
        return sb.toString();
    }
    
    // this method is complete, do not alter it
    private static String quoteWrap(String s) {
        if ( s == null ) {
            return "null";
        } else {
            return '"' + s + '"';
        }
    }

    // this method is complete, do not alter it
    private static void process(String[] set) {
        System.out.println("Original String[]: " + format(set));
        System.out.printf("  %3d   - count%n", getCount(set));
        System.out.printf("  %3d   - shortest length (%s)%n", 
            getShortestLength(set), quoteWrap(getFirstShortest(set)));
        System.out.printf("  %3d   - longest length (%s)%n", 
            getLongestLength(set), quoteWrap(getFirstLongest(set)));
        System.out.printf("  %5.1f - average length%n", getAverageLength(set)); 
        System.out.printf("  %3d   - total length%n", getTotalLength(set));
        sortLength(set);
        System.out.println("after length sort: " + format(set));
        System.out.println("----------");
    }
    
    // this method is complete, do not alter it
    public static void main(String[] args) {
        process(new String[] { "apple" });
        process(new String[] { "watermelon", "grape" });
        process(new String[] { "pear", "date" });
        process(new String[] { "cherry", "apple", "pear", "grape", "banana" });
        
        
        // Zero-length strings are OK, they just have a length of zero
        process(new String[] { "" });
        process(new String[] { "", "apple", "", "cherry", "banana" });
                
        // A zero-length array
        process(new String[0]);
        
        // No array at all, just null passed in
        process(null);
        
        // Some slots contain null instead of a String
        process(new String[] { null });
        process(new String[] { null, null });
        process(new String[] { null, "apple", null });
        process(new String[] { null, "", null });
        process(new String[] { null, "apple", null, "cherry", "banana" });
        
        
    }
}

I am obtaining an ArrayIndexOutOfBounds exception when attempting to calculate the length of the zero-length array. Are you able to tell me if I'm overlooking something?

The exception should include a line number, which will help you locate where exactly the problem is.

Keep in mind, for a zero-length array, even index 0 is out of bounds. There are no elements at all in the array.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.