[英]What's wrong with my constructor in this moving x matrix?
这个想法是每次迭代都会在每次打印时移动 [x]。 但是它显然不能打印 0x0 矩阵。 如您所见,我在程序中调用了构造函数来获取变量 4、4。但由于某种原因,运行它后,程序仍然输出 0,0。
公共 class MovingX{
private int rowsN;
private int columnsM;
private int[][] matrixArr = new int[rowsN][columnsM];
private int x = 0;
private int y = 0;
public MovingX(int n, int m){
n = rowsN;
m = columnsM;
}
public void forLoopGrid(){
for(int i = 0; i < matrixArr.length; i++){
for(int j = 0; j < matrixArr.length; j++){
if(i == x && j == y) System.out.print("[x] ");
else System.out.print("[ ] ");
}
System.out.println();
}
System.out.println();
}
public void moveX(){
if(x < rowsN) x++;
else{
x = 0; y++;
}
}
public void runProgram(){
System.out.println("Program Starting");
System.out.println("Rows, Columns: " + rowsN + " " + columnsM);
for(int i = 0; i < (rowsN * columnsM); i++){
System.out.println("Stuff happening");
forLoopGrid();
moveX();
}
System.out.println("Program Ending");
}
public static void main(String[] args){
MovingX xLoop = new MovingX(4, 4);
xLoop.runProgram();
}
}
原因可能与作业有关。
public MovingX(int n, int m){
rowsN = n;
columnsM = m;
}
试试这个,他们可能会工作。
肯定是这个问题,谢谢。 现在我遇到的唯一问题是代码允许打印一个空白数组,因为有一个点 j = 0. 和 y = 1。现在想办法解决这个问题。
问题似乎是您将对象的字段(rowsN,columnsM)分配给提供给 class 构造函数的参数(n,m)。
您会看到,当您使用那些本地构造函数变量来存储对象字段的默认值时,您在实例化期间提供什么 arguments 并不重要。 您得到 (0,0),因为所有 object 字段都被初始化为默认值,而对于 int,恰好为 0。
这应该工作 -
public MovingX(int n, int m){
rowsN=n; //n = rowsN;
columnsM=m; //m = columnsM;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.