Question

I have to write a static method called "count" taking a char as parameter that will return the number of times that this char occurs in Layout.ROWS (array of strings in class Layout). To do that I need an outer loop to loop over each row and nested loop to loop over each character. This is what I tried:

public static int count(char d)
{
    int sum = 0; 
    int i = 0;

     while ( i < Layout.ROWS.length && !Layout.ROWS[i].equals(d) ) 
     {  
         i++;

         if (Layout.ROWS[i].equals(d))
         {
            sum++;
         }
     }   

     return sum;
}

But it is not working. My output is: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException

Any idea of how I should do it? This is Layout.ROWS:

public static final String[] ROWS = {
    "     p      ex",
    " .            ",
    "  .           ",
    "   .          ",
    "    .         "
};
Was it helpful?

Solution

You're attempting to compare a string (Layout.ROWS[i]) to a char. You should iterate over the Strings in your array, and for each such String iterate over the chars that make it up. While this can be acheived with a while loop, using for loops would be much cleaner:

public static int count(char d) {
    int sum = 0; 

    // Iterate over all the strings in Layout.ROWS:
    for (String str : Layout.ROWS) {
        // Iterate over the chars of the string:
        for (int i = 0; i < str.length(); ++i) {
            if (d == str.charAt(i)) {
                ++sum;
            }
        }
    }
    return sum;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top