gpt4 book ai didi

java - Java 代码中的无限循环

转载 作者:行者123 更新时间:2023-11-30 04:29:33 25 4
gpt4 key购买 nike

我的程序中存在有关无限循环以及不正确响应的问题。在我的程序中,我试图为战舰游戏随机设置船只,但在放置船只部分时遇到问题。我已经对其进行了编码,但遇到了两个问题,一个是我在某个地方有一个无限循环,但我不知道在哪里,另一个是这些部分没有在网格上正确设置。我已经查看这段代码很长时间了,但还没有找到解决办法。这是:

    public void placeAllShips() {
int direction = (int) Math.random()*2 ;
int p1 = 0 ;
int p2 = 0 ;
for(int ships = 1 ; ships < 6 ; ships ++ ) {
p1 = (int)(Math.random()*10);
p2 = (int)(Math.random()*10);
if ( p1 !=0 && p2!= 0 && direction == 0 /* Horizontal Direction*/ ){
for(int i= 0; i < ships ; i ++ ){
while(board[p1][p2+i].hasShip() == true || p2 + i > 10 && p2 - i < 0 ){
randomize(p1,p2) ;
}
}
for(int j = 0 ; j < ships ; j ++ ) {
board[p1][p2+j].setHasShip(true) ;
}

}
else if ( p1 !=0 && p2!= 0 && direction == 1 /*Vertical Direction*/ ){
for(int i= 0; i < ships ; i ++ ){
while(board[p1+i][p2].hasShip() == true || p1 + i > 10 && p1 - i < 0 ){
randomize(p1,p2) ;
}
}
for(int j = 0 ; j < ships ; j ++ ) {
board[p1+j][p2].setHasShip(true) ;
}

}
}
}

public void randomize( int x , int y ) {
//Generates random numbers.
x = (int)Math.random()*10 ;
y = (int)Math.random()*10 ;
}

感谢您的帮助!

最佳答案

我怀疑无限循环是由于不了解参数传递在Java中的工作原理引起的。看一下这段代码:

// You're calling this if you're trying to use a point which is already taken
randomize(p1,p2) ;

public void randomize( int x , int y ) {
//Generates random numbers.
x = (int)Math.random()*10 ;
y = (int)Math.random()*10 ;
}

除了使用 Random 的单个实例而不是 Math.random() 更清晰的事实之外,您的 randomize() code> 方法从根本上没有按照您期望的那样执行。

当您调用 randomize(p1, p2) 时,会将 p1p2复制到参数xy作为初始值。对 xy 的更改不会改变 p1p2...所以如果您完全进入该循环,它将是无限的,因为 p1p2 在每次迭代中都是相同的。

首先,您可能应该将循环更改为:

// Put this *outside* the top level loop so you only create a single instance
Random random = new Random();

...

while(p2 + i > 10 || p2 - i < 0 || board[p1][p2+i].hasShip()) {
p1 = random.nextInt(10);
p2 = random.nextInt(10);
}

无论如何,这都不是完整的解决方案(您的代码还存在其他问题),但尝试一次理解一个问题很重要。

(接下来要考虑的事实是,您需要在单个点检查一艘船的所有值 - 您需要选择一个点,然后尝试一艘船的所有方 block 此时会占用时间,如果失败,您需要重新开始,而不是仅仅尝试不同的点来获取 i 的值。)

关于java - Java 代码中的无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14996990/

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