Skip to content

Commit a2c19bc

Browse files
committed
feat: Count strings in 2D array that contain the letter 'a'
🧠 Logic: - Define a static method `count` that accepts a 2D array of strings. - Use nested loops to iterate through all elements in the array. - For each string, use `indexOf("a")` to check if it contains the character 'a'. - If found, increment the `count`. - In `main`, define a 2D string array `items`, call `count`, and print the total number of strings that contain 'a'. Signed-off-by: Somesh diwan <[email protected]>
1 parent 1f56cfa commit a2c19bc

File tree

1 file changed

+26
-9
lines changed

1 file changed

+26
-9
lines changed
Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,35 @@
1-
public class CountingError
2-
{
1+
public class CountingError {
32
public static int count(String[][] things)
3+
/*
4+
static method named count that, Returns an int (the count), Takes a 2D array of strings (String[][] things) as input
5+
*/
46
{
5-
int count = 0;
6-
for (int r = 0; r < things.length; r++)
7-
{
8-
for (int c = 0; c < things[r].length - 1; c++)
9-
{
10-
if (things[r][c].indexOf("a") >= 0)
11-
{
7+
int count = 0; //keep track of how many strings in the array contain the letter 'a'
8+
9+
//r represents the row index.
10+
//things.length gives the total number of rows in the 2D array.
11+
for (int r = 0; r < things.length; r++) {
12+
/*
13+
c is the column index.
14+
things[r].length gives the number of columns in the r-th row.
15+
It ensures we visit every element in the 2D array.
16+
*/
17+
for (int c = 0; c < things[r].length; c++) {
18+
if (things[r][c].indexOf("a") >= 0) {
1219
count++;
1320
}
1421
}
1522
}
1623
return count;
1724
}
25+
26+
public static void main (String[]args) {
27+
String[][] items = {
28+
{"apple", "banana", "cherry"},
29+
{"dog", "cat", "rat"},
30+
{"hat", "bat", "mat"}
31+
};
32+
int result = count(items);
33+
System.out.println("Count of strings containing 'a': " + result);
34+
}
1835
}

0 commit comments

Comments
 (0)