2014-07-27 74 views
-4

我想學習java,當然我是初學者。我面臨初始化多維數組時遇到的問題。這裏是我想寫的代碼...多維數組初始化遇到問題

import java.util.Scanner; 
public class one { 

    public static void main(String args[]) { 
     int p[][] = null; 
     System.out.println("Type ur array here:"); 
     System.out.println("how many rows and column:"); 
     int row, colmn; 
     Scanner u = new Scanner(System.in); 
     Scanner y = new Scanner(System.in); 
     Scanner t = new Scanner(System.in); 
     Scanner r = new Scanner(System.in); 

     row = t.nextInt(); 
     colmn = r.nextInt(); 

     for(int i = 0; i <= row; i++) 
      for(int v = 0; v <= colmn; v++){ 
       int j = u.nextInt(); 
       p[row][colmn] = j; 
      } 

     int a[][] = p; 
     System.out.println("The given array:"); 
     y(a); 

    } 
    public static void y(int n[][]) { 

     for(int i=0;i<n.length;i++) { 
      for(int j=0;j<n[i].length;j++){ 
       System.out.print(n[i][j]); 
      } 
      System.out.println(); 
     } 
    } 

} 

請有人糾正這一點,併爲我提供足夠的知識,我需要。

+5

可以初始化與'INT多維數組[] [] P =新INT [容量] [captacity]; ' – August

+1

@八卦或者'int [] [] p = new int [capacity] []'而不是。請注意,第二個容量可以留空,在這種情況下,可以用'p [index] = new int [capacity]'自由地建立第二個維數組。 – Unihedron

+0

另外,___請使用描述性變量名稱。 – Unihedron

回答

1

更改到代碼中的註釋中提到,但請參見下面的代碼:

import java.util.Scanner; 

public class one { 

    public static void main(String args[]) { 
     int p[][] = null; 
     System.out.println("Type ur array here:"); 
     System.out.println("how many rows and column:"); 
     int row, colmn; 
     Scanner u = new Scanner(System.in); 

     // Only one is required to read from standard input stream, instead of: 
     // Scanner y = new Scanner(System.in); 
     // Scanner t = new Scanner(System.in); 
     // Scanner r = new Scanner(System.in); 

     // Use Scanner object "u": 
     row = u.nextInt(); 
     colmn = u.nextInt(); 

     // Memory to array: 
     p = new int[row][colmn]; 

     // Change '<=' to '<' as arrays are 0 index and will give index out of bounds exception ; 
     // Or change 'p = new int[row][colmn];' to 'p = new int[row + 1][colmn + 1];'. 
     for(int i = 0; i < row; i++){ 
      for(int v = 0; v < colmn; v++){ 
       int j = u.nextInt(); 
       // Change indices to "i, v" instead of "row, colmn": 
       p[i][v]=j; 
      } 

     } 
     // Bad way to copy array as same reference is going to be used. 
     // To copy array use the following: 

     /* 
     * // int a[][] = p; 
     * int[][] a = new int[row][colmn]; 
     * for (int i = 0; i < row; i++) { 
     *  System.arraycopy(p[i], 0, a[i], 0, colmn); 
     * } 
     */ 

     int a[][] = p; 
     System.out.println("The given array:"); 
     y(a); 

    } 
    public static void y(int n[][]){ 

     for(int i = 0; i < n.length; i++){ 
      for(int j = 0; j < n[i].length; j++) 
       System.out.print(n[i][j]); 
      System.out.println(); 
     } 
    } 

}