Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a simple 4x3 two dimensional array in Java?

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);


}
}
like image 754
Ben Avatar asked Apr 15 '26 02:04

Ben


2 Answers

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));
like image 184
Elliott Frisch Avatar answered Apr 17 '26 14:04

Elliott Frisch


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));
    }
}
like image 20
Rajen Raiyarela Avatar answered Apr 17 '26 14:04

Rajen Raiyarela



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!