2014-07-27 39 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(); 
     } 
    } 

}