帮我解决这个 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
复制构造函数中应该包含什么内容才能创建与 m2 阶数相同的新矩阵 m3?
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();
}
}
注意:除了数组 a 之外,不能使用任何额外的实例变量。
接受的答案:@Chankey:this(b1.a.length,b1.a[0].length); – 约翰
Question:
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
What should be there in the copy constructor to make a new matrix m3 of the same order as of 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();
}
}
NOTE: You can not use any extra instance variable except the array a.
Accepted answer: @Chankey: this(b1.a.length,b1.a[0].length); – John
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
将行数和列数存储在矩阵类中,并为它们创建 getter。
Store the number of rows, and the number of columns in the matrix class, and create getters for them.
您需要获取传递的
b1
矩阵的大小,然后使用它来构造最终数组。
You need to get the size of the passed
b1
matrixand can then use it to construct the final array.
使用
但不推荐。
你应该有一些 get 方法,它返回
矩阵维数。
Use
But it is not recommended .
you should have some get method , which return
matrix dimension.
这是作业,所以我会给你一个提示:
你如何获得 b1 的二维矩阵 (
a[][]
) 的长度?矩阵类中的正确方法会有所帮助 - 您将如何实现这些(getX,getY)?另外,最好将构造函数重定向到最详细的构造函数,例如:
This is homework, so I'll give you a hint:
How would you get the lengths of the 2 dimensional matrix (
a[][]
) of b1? proper methods in the matrix class will help - how would you implement those (getX, getY)?Also, it is better to redirect the constructors to the most detailed one, for example:
这可能是最可能的答案,无需使用除数组本身之外的任何其他实例变量:
}
This can be the most probable answer without using any other instance variable other then the array itself:
}