2011-04-15 87 views
0

问题帮我这个Java代码

matrix m1 = new matrix(); // should produce a matrix of 3*3 

matrix m2 = new matrix(5,4); //5*4 

matrix m3 = new matrix(m2); //5*4 

应该是什么那里的拷贝构造函数,使同一顺序的一个新的矩阵M3为M2的?

public class matrix { 

    int a[ ][ ]; 

     matrix(){ 
     a = new int[3][3]; 
     } 

    matrix(int x, int y){ 
     a= new int [x][y];  
     } 

    matrix (matrix b1){   
     //how to use value of x and y here.... 
     } 

void show(){ 

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




public class matrixtest { 

public static void main(String [ ] args){ 

     matrix a = new matrix();  
     matrix b = new matrix(5,4); 
     matrix c = new matrix (b); 
     a.show(); 

     b.show(); 

     c.show(); 
    } 

} 

注意:您不能使用任何额外的实例变量数组时除外。

接受的答案:@Chankey:this(b1.a.length,b1.a [0] .length); - John

+0

使用一个新的= INT [b1.a.length] [b1.a [0]。长度]。 – 2011-04-15 10:20:04

+1

'this(b1.a.length,b1.a [0] .length);' – 2011-04-15 10:20:45

+0

只需要添加,它是**首选**,您的类名以大写字母开头。 – 2011-04-15 10:25:39

回答

6

存储矩阵类中的行数和列数,并为它们创建getter。

+1

对于面向对象和封装答案(不直接访问'b.a')! – MByD 2011-04-15 10:27:57

+0

谢谢,但我知道这种方法。我被要求在不使用任何实例变量的情况下解决问题。约翰已经在评论中给出了解决方案,但我认为我也应该接受你的答案。 :) – 2011-04-15 17:16:42

1

你需要获得通过b1矩阵

int x = b1.length; 
int y = b1[0].lenght; 

的大小,然后可以用它来构建最终阵列。

a= new int [x][y]; 
+0

b1没有长度属性,它不是数组。 – MByD 2011-04-15 10:21:16

+1

+1虽然它应该是“b1.a.length” – pablochan 2011-04-15 10:21:33

1

使用

a =new int[b1.a.length][b1.a[0].length]; 

但不推荐使用。 你应该有一些get方法,它返回 矩阵的维数。

1

这是家庭作业,所以我会给你一个提示:

你将如何获得b1的2维矩阵(a[][])的长度?矩阵类中的适当方法将有所帮助 - 你将如何实现这些(getX,getY)?

而且,最好是所述构造重定向到最详细的一种,例如:

matrix(){ 
    this(3,3); // call the constructor below with parameters 3,3 
    } 

matrix(int x, int y){ 
    a= new int [x][y];  
    } 
0

这可以是最可能的答案,而无需使用任何其他实例变量其他然后数组本身:

import java.io.*; 
class matrix 
{ 
private int arr[][]; 
public matrix() //Default Constructor 
{ 
    this(3,3); 
} 

public matrix(int r,int c) //Parameterized Constructor 
{ 
    arr=new int[r][c]; 
    read(); 
} 

public matrix(matrix m) //Copy Constructor 
{ 
    System.out.println("Fetching array..."); 
    int r,c; 
    r=m.arr.length; 
    c=m.arr[0].length; 
    arr=new int [r][c]; 
    for(int i=0;i<r;i++) 
    { 
     for(int j=0;j<c;j++) 
     { 
      arr[i][j]=m.arr[i][j]; 
     } 
    } 
} 

public void read() 
{ 
    int i,j,r,c; 
    r=arr.length; 
    c=arr[0].length; 
    Console con=System.console(); 
    for(i=0;i<r;i++) 
    { 
     for(j=0;j<c;j++) 
     { 
      arr[i][j]=Integer.parseInt(con.readLine()); 
     } 
    } 
} 
public void show() 
{ 
    int i,j; 
    for(i=0;i<arr.length;i++) 
    { 
     for(j=0;j<arr[0].length;j++) 
     { 
      System.out.print(" "+arr[i][j]); 
     } 
     System.out.println(); 
    } 
} 

}