Results 1 to 2 of 2
  1. #1
    iLearnJava is offline Member
    Join Date
    Dec 2014
    Posts
    3
    Rep Power
    0

    Default Multi-Dimensional arrays [SOLVED]

    I want to print each value in the multi-dimensional array using a for loop but there is a problem.
    Here is the script:
    Java Code:
    public class LearningJava 
    {
    	public static void main(String[] args) 
    	{
    		int[][] Grid = {
    				{12, 24, 36, 48, 60},
    				{1, 3, 5},
    				{5, 25, 125, 625}
    		};
    		for(int i = 0; i < Grid.length; i++) {
    			for(int x = 0; x < Grid[i][x]; x++) {
    				System.out.println("Printing i: " + i + ", x: " + Grid[i][x]);
    			}
    			System.out.println("Switching to i: " + i);
    		}
    	}
    }
    I'm using the "Eclipse" editor and this is the output:
    Printing i: 0, x: 12
    Printing i: 0, x: 24
    Exception in thread "main" Printing i: 0, x: 36
    Printing i: 0, x: 48
    Printing i: 0, x: 60
    java.lang.ArrayIndexOutOfBoundsException: 5
    at LearningJava.main(LearningJava.java:11)

    It's suppose to get the length of each array and print all the values in that array and then move to the next one.
    I tried adding .length
    Java Code:
    for(int x = 0; x < Grid[i][x].length; x++)
    but then it doesn't work at all.
    Last edited by iLearnJava; 12-05-2014 at 01:46 PM.

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,007
    Rep Power
    34

    Default Re: Multi-Dimensional arrays [SOLVED]

    it doesn't work at all.
    Please explain.

    .length is a field of an array.
    With a 2 dim array, the length of the second dim would be: theArray[firstDimIndex].length
    With a 3 dim array, the length of the third dim: theArray[firstDimIndex][secondDimIndex].length
    If you don't understand my response, don't ignore it, ask a question.

Similar Threads

  1. Replies: 4
    Last Post: 06-28-2014, 06:00 PM
  2. Replies: 4
    Last Post: 03-09-2011, 06:54 AM
  3. Replies: 4
    Last Post: 08-01-2010, 10:25 AM
  4. Multi-dimensional arrays
    By Implode in forum New To Java
    Replies: 1
    Last Post: 09-15-2009, 09:50 AM
  5. [SOLVED] Multi-dimensional arrays
    By thelinuxguy in forum Advanced Java
    Replies: 3
    Last Post: 05-07-2009, 03:52 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •