0

I want to create an multidimensional array that will count. This is the code I have so far and don't know where to go from here. When I print this out I want it to look like 0,1,2,3,4,5,6,7,8,9,10,etc.

public static void main(String[] args) {

        int car[][] = new int[4][4];

        for(int row = 0; row < car.length; row++){
            for(int col = 0; col < car[1].length; col++){
                System.out.print(car[row][col] + ",");
            }
            System.out.println();
        }

    }

1
  • Hi! What's last item you expect in the series? In other words, to which value to you wish to count? Keep in mind your array values haven't been initialized yet. All the values will be zero at this stage. Commented Apr 6, 2020 at 4:52

3 Answers 3

1

you're creating empty array so every field has value 0

try this:

public static void main(String[] args) {

        int car[][] = new int[4][4];

        int index = 0;

        for(int row = 0; row < car.length; row++){
            for(int col = 0; col < car[1].length; col++){
                car[row][col] = index++;
                System.out.print(car[row][col] + ",");
            }
            System.out.println();
        }

    }
Sign up to request clarification or add additional context in comments.

Comments

0

You need to set the values before printing them

    for(int row = 0; row < car.length; row++){
        for(int col = 0; col < car[1].length; col++){
            car[row][col] = row * 4 + col;
            System.out.print(car[row][col] + ",");
        }
        System.out.println();
    }

But it's silly and pointless to use a multi-dimensional array like this.In my experience, Multi-dimensional arrays are useful in a much more limited scope than how people play with them when they are learning.

Comments

0

Use this:

public static void main(String[] agrs) {


    int car[][] = new int[4][4];
    int i = 0;

    for(int row = 0; row < car.length; row++){

        for(int col = 0; col < car[1].length; col++){
            car[row][col] = i++;                
            System.out.print(car[row][col] + ",");
        }

    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.