2016-02-26 69 views
3

我已經把它放在C++中,但Java對我來說更具挑戰性。這是我的。我只是希望它有4行3列初始化爲1-12並將其打印到屏幕上。我的錯誤是否對你顯而易見?謝謝!如何在Java中創建一個簡單的4x3二維數組?

我拿到13個錯誤:(

包括line9:twoDArray [] []不聲明;預計,非法 開始表達,所有的幾次每次

代碼我想:

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


} 
} 
+1

PL添加您的原職,爲此分裂婷請創建單獨的問題。 –

+0

我會,但我刪除了原始上下文。我不會再說,對不起。 – Ben

+0

我加回原來的問題文本,PL接受編輯並創建另一個問題。 –

回答

5

首先,陣列(甚至是二維數組)不重寫Object.toString您可以使用Arrays.deepToString(Object[])和init。在聲明時ialize你的數組。像

int[][] twoDArray = new int[][] { 
     { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, { 10, 11, 12 } 
}; 
System.out.println(Arrays.deepToString(twoDArray)); 
+1

非常感謝! Arrays.deepToString()呵呵..我學到了一些新東西! – Ben

1

東西已修改了代碼

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)); 
    } 
} 
+0

感謝一羣朋友! – Ben

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)); 
} 
} 
+2

非常感謝! Arrays.deepToString()呵呵..我學到了一些新東西!讚賞。 – Ben

0

以下是完整的工作拷貝

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(""); 
    } 
} 

}

+0

謝謝!現在我編輯了我的問題,你能幫我解決嗎? – Ben

+0

是的,因爲在這種情況下不允許數組初始化 – Abhishek