gpt4 book ai didi

java - 通过引用更新对象(数独)

转载 作者:行者123 更新时间:2023-12-02 07:10:45 26 4
gpt4 key购买 nike

我有一个数独谜题求解器,需要我们使用递归。问题是我检查可用空间的 boolean 值应该通过引用更新当前位置,但事实并非如此。什么会导致这个?

    public boolean solve()
{
Coordinate current = new Coordinate();

if (findEmptyGridSlot(current)) { // THE ERROR IS HERE ********** THIS IS SHOWING (0,0) STILL ******************

for (int number = 1; number <= 9; number++)
if (canPlaceNumber(current, number)) {
grid[current.getRow()][current.getColumn()] = number;

if (solve())
return true;

grid[current.getRow()][current.getColumn()] = 0;
} return false;
}else
return true;

}

private boolean findEmptyGridSlot(Coordinate coordinate)
{
boolean found = false;

try{
while (!found)
{
if (grid[coordinate.getRow()][coordinate.getColumn()] == 0)
found = true;
else
coordinate = coordinate.next(); // *****This is supposed to update the current coordinate ******
}
}catch (Exception e){
//CREATE No Empty Cells Exception
}
return found;
}

public Coordinate next()
{
Coordinate result = new Coordinate(row, column);

result.column++;
if (result.column > MAX_COORDINATE)
{
result.column = MIN_COORDINATE;
result.row++;
if (result.row > MAX_COORDINATE) result = null;
}

return result;
}

最佳答案

Java 按值传递。这意味着您将获得坐标引用的副本。如果您将该副本指向一个新对象(即坐标=坐标.下一个),您只是更改本地副本。现在,另一方面,如果您更改了变量所引用的对象的属性(例如,coordinate.x = foocoordinate.setX(foo)),该属性也会发生变化对您的方法的调用者可见。

关于java - 通过引用更新对象(数独),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15558637/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com