一直在尝试使用Java的堆栈/回溯来解决n皇后问题。不是很有经验,试着看看我哪里出错了 publicstaticvoidmain(字符串[]args){ 代码冲突中的while(filled
将永远不会为真;因为布尔数据类型是按值传递的。请参见下面的示例:一直在尝试使用Java的堆栈/回溯来解决n皇后问题。不是很有经验,试着看看我哪里出错了 publicstaticvoidmain(字符串[]args){ 代码冲突中的while(filled,java,loops,stack,Java,Loops,Stack,将永远不会为真;因为布尔数据类型是按值传递的。请参见下面的示例: public static void conflictTest(boolean conflict) { for (int i = 1; i < xPosition.size(); i++) { int j = xPosition.size()-i; if (x == xPosition.get(i) || x == xPosition.get(i) + j
public static void conflictTest(boolean conflict) {
for (int i = 1; i < xPosition.size(); i++) {
int j = xPosition.size()-i;
if (x == xPosition.get(i) || x == xPosition.get(i) + j
|| x == xPosition.get(i) - j) {
conflict = true;
}
}
}
为了解决这个问题,你应该改变你的功能
public class Test{
public static void makeMeTrue(boolean youThinkIamTrue)
{
//local value set to true but your original youThinkIamTrue still false
youThinkIamTrue = true;
}
public static void main(String []args){
boolean youThinkIamTrue = false;
makeMeTrue(youThinkIamTrue);
//will print false
System.out.println(youThinkIamTrue);
}
}
我看不到将冲突更新为true的代码,冲突是全局变量吗?@MohdAlomar我在原始帖子中添加了一个编辑
public class Test{
public static void makeMeTrue(boolean youThinkIamTrue)
{
//local value set to true but your original youThinkIamTrue still false
youThinkIamTrue = true;
}
public static void main(String []args){
boolean youThinkIamTrue = false;
makeMeTrue(youThinkIamTrue);
//will print false
System.out.println(youThinkIamTrue);
}
}
public static boolean conflictTest(boolean conflict) {
for (int i = 1; i < xPosition.size(); i++) {
int j = xPosition.size()-i;
if (x == xPosition.get(i) || x == xPosition.get(i) + j
|| x == xPosition.get(i) - j) {
return true;
}
}
return conflict;
}
conflict = conflictTest(conflict);