3

I've got it down in C++, but Java is proving more challenging to me. Here's what i have. I simply want it to have 4 rows and 3 columns initialized to 1-12 and to print it to the screen. Are my errors apparent to you? Thanks!

I get 13 errors :(

including line9:twoDArray[][] not a statement, ; expected, illegal start of expression, all a few times each.

Code i tried:

import java.util.*;


class twoDimensional array
{ public static void main(String args[])
{
int[][] twoDArray = new int[4][3];

twoDArray[][]={{1,2,3},{4,5,6},{7,8,9},{10,11,12}};

System.out.print(twoDArray.toString);


}
}
vefthym
  • 7,422
  • 6
  • 32
  • 58
Ben
  • 111
  • 2
  • 9

4 Answers4

5

First, arrays (even 2d arrays) don't override Object.toString. You can use Arrays.deepToString(Object[]) and initialize your array when you declare it. Something like

int[][] twoDArray = new int[][] { 
        { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, { 10, 11, 12 } 
};
System.out.println(Arrays.deepToString(twoDArray));
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

Have modified your code

import java.util.*;

class twoDimensional array
{ 
    public static void main(String args[]){
      int[][] twoDArray = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};
      //For printing array you have to do 
      System.out.print(Arrays.deepToString(twoDArray));
    }
}
Rajen Raiyarela
  • 5,526
  • 4
  • 21
  • 41
1
import java.util.*;

class twoDimensionalArray
{ 
public static void main(String args[])
{
int[][] twoDArray = new int[][] { 
    { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, { 10, 11, 12 } 
};
System.out.println(Arrays.deepToString(twoDArray));
}
}
Anurag Goel
  • 468
  • 10
  • 15
0

Here Is The Full Working Copy

public class TwoD {

public static void main(String... args)
{
    int [][]twoD = new int[4][3];
    int num = 1;

    for(int i = 0; i < 4; i++)
    {
        for(int j = 0; j < 3; j++)
        {
            twoD[i][j] = num;
            num++;
        }
    }

    for(int i = 0; i < 4; i++)
    {
        for(int j = 0; j < 3; j++)
        {
            System.out.print(twoD[i][j]+"\t");
        }
        System.out.println("");
    }
}

}

Abhishek
  • 3,348
  • 3
  • 15
  • 34