【发布时间】:2021-12-04 16:06:09
【问题描述】:
问题:
为什么第二个构造函数不接受第一个构造函数的对象作为输入?
在代码的更一般概述中,如果你们发现任何有问题的逻辑问题,如果您能指出它们,我将非常感激。
import java.util.Scanner;
public class Square3x3{
private static final int DEF_VALUE = -1;
private static final int ROW_COUNT = 3;
private static final int COL_COUNT = 3;
private static final int LOWER_BOUND = 0;
private int [][] _square;
public Square3x3(){
_square = new int [ROW_COUNT][COL_COUNT];
for(int i = 0 ; i < ROW_COUNT ; i++)
{
for (int j = 0; j < COL_COUNT; j++)
{
_square[i][j] = DEF_VALUE;
System.out.print(_square[i][j]);
}
System.out.println();
}
}
public Square3x3(int[][]array){
int rows = array.length;
int column;
int colCount = 0;
for(int j = 0; j < rows; j++){
colCount = j;
}
column = colCount;
if (rows > ROW_COUNT || column > COL_COUNT){
for (int k = 0; k < ROW_COUNT; k++)
for (int g = 0 ; g < COL_COUNT; g++){
_square[k][g] = array[k][g];
}
}
if (rows < 3 || column < 3){
for (int x = 0; x > array.length; x++)
for (int y = 0 ; y > array.length; y++){
array[x][y] = -1;
}
}
if (rows == 3 && column == 3){
for (int i = 0; i < array.length; i++){
for (int j = 0; j < array.length; j++){
_square[i][j] = array[i][j];
}
}
}
}
public Square3x3(Square3x3 other){
if (other != null){
other = new Square3x3();
for (int i = 0; i < ROW_COUNT; i++)
for (int j = 0; j < COL_COUNT; j++){
this._square[i][j]=other._square[i][j];
}
}
}
【问题讨论】:
-
other = new Square3x3();你正在重新初始化对象,值被重置并且你正在复制 reset(-1) 值 -
不清楚你在问什么。构造函数必须带有
new及其适当的参数。构造函数本身不会调用另一个构造函数(除非您需要同一对象的另一个实例,否则这样做是没有意义的)。你的意思是让构造函数调用非 ctor 方法吗? -
Square3x3() 输出一个元素为 -1 的 3x3 矩阵。如果我创建这种类型的对象,如何将其输入到 Square3x3(int[][]array)?
-
为此,您需要一个用于
_square属性的 getter 方法,以便您可以访问它。但是现在我对您的实际问题更加困惑。 -
您对 Square3x3(Square 3x3 other)构造函数很满意。至于上面的问题,它们是无关的。
标签: java constructor