简体   繁体   中英

2D Arrays In Java - Not Printing

String[][] arrays = {
        {"Hello","World","Matt"},
        {"Computer","Good","Keyboard","Mouse"}
    };
    for(int r = 0; r < arrays.length; r++)
    {
        for(int c = 0; c < arrays[0].length; c++)
        {
            System.out.print(arrays[r][c]);
        }
    }

The result that I am getting from this is "HelloWorldMattComputerGoodKeyboard" where Mouse is not being included in this array.

The rows of your array don't have the same length. Change your loop to :

for(int r = 0; r < arrays.length; r++)
{
    for(int c = 0; c < arrays[r].length; c++)
    {
        System.out.print(arrays[r][c]);
    }
}

You have problem in your inner loop where you are iterating 0 indexed array length every time, your 0th indexed arrays length is 3 that's why your mouse is not printing because your 2nd array's length is 4 ,try replacing 0 with r inside nested loop.

for(int r = 0; r < arrays.length; r++)
    {
        for(int c = 0; c < arrays[r].length; c++)
        {
            System.out.print(arrays[r][c]);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM