Search code examples
javaarraysbreak

Jagged Array & Nested For Loop in Java


I have what I thought was a very basic code example, but I can't figure out why the code never completes. It seems to stay stuck in a loop. This very simple code is supposed to declare and initialize a jagged array with the first row having 4 columns and the second row having 3 columns. The code asks the user for 7 integers and prints out the result to the screen. All of that works, but it doesn't break out of the loop unless I manually break out of it. If the manual break is used, the correct output is not achieved.

public class TestCode {

    public static void main(String[] args) {
        //Create new scanner object
        Scanner userInput = new Scanner(System.in);
        //Declare two dimentional array
        int[][] num2d = new int[4][3];
        //Declare variables
        int i;
        int j;
        //Print to screen asking for user input
        System.out.print("Enter seven numbers: ");

        //Loop through array and print the result
        for (i = 0; i < num2d.length; i++) {
            for (j = 0; j < num2d[i].length; j++) {
                num2d[i][j] = userInput.nextInt();
                System.out.println(num2d[i][j]);
                //break;
            }
        }
    }
}

When I run this code with the break commented out, I get this result, but I have to manually stop it from running.

run:
Enter seven numbers: 1 2 3 4 1 2 3

1
2
3
4
1
2
3

When I put the break in, this is what I get.

run:
Enter seven numbers: 1 2 3 4 1 2 3

1
2
3
4
BUILD SUCCESSFUL (total time: 4 seconds)

What's going on? Why can I get the correct result with the "build successful" message without using the break?


Solution

  • Your code doesn't loop forever: it loops 12 times, because you have declared a 4x3 array - i.e. an array sized 4 where each of the elements is an array of 3 ints.

    Instead, I think you want something like this:

    int[][] num2d = {new int[4], new int[3]};