Skip to content

Commit c4b4191

Browse files
committed
fix: Correct 2D array initialization and iterate over letters and numbers
🧠 Logic: - Declared a 2D `String` array `letters` of size `[3][4]` but initialized each row with 5 elements instead of 4 — this causes `ArrayIndexOutOfBoundsException`. - Fixed the mismatch: either reduce each row to 4 elements or change declaration to `[3][5]`. - Used enhanced for-loops to print letters row by row. - Declared and printed 2D `int` array `numbers` using traditional nested loops. Signed-off-by: Somesh diwan <[email protected]>
1 parent 7d13cac commit c4b4191

File tree

1 file changed

+9
-14
lines changed

1 file changed

+9
-14
lines changed
Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,27 @@
1-
public class Arrays2D
2-
{
3-
public static void main(String[] args)
4-
{
1+
public class Arrays2D {
2+
public static void main(String[] args) {
53
//Create a 2D array of Strings, with 3 rows and 4 columns
64
String[][] letters = new String[3][4];
5+
76
letters[0] = new String[]{"a", "b", "c", "d", "e"};
87
letters[1] = new String[]{"f", "g", "h", "i", "j"};
98
letters[2] = new String[]{"k", "l", "m", "n", "o"};
109

1110
//Enhanced for loop where every iteration, row is a 1D array of Strings.
12-
for (String[] row: letters)
13-
{
14-
//Enhanced for loop where letter is each element of the current row.
15-
for (String letter: row)
16-
{
11+
for (String[] row: letters) {
12+
//Enhanced for loop where a letter is each element of the current row.
13+
for (String letter: row) {
1714
System.out.print(letter);
1815
}
1916
System.out.println();
2017
}
2118

2219
int[][] numbers = {{1,2}, {3,4}, {5,6}, {7,8}};
23-
for (int y=0; y < numbers.length; y++)
24-
{
25-
for (int x = 0; x < numbers[0].length; x++)
26-
{
20+
for (int y=0; y < numbers.length; y++) {
21+
for (int x = 0; x < numbers[0].length; x++) {
2722
System.out.print(numbers[y][x]);
2823
}
2924
System.out.println();
3025
}
3126
}
32-
}
27+
}

0 commit comments

Comments
 (0)