gpt4 book ai didi

java - 如何删除其中一个 if 语句并缩短代码?

转载 作者:行者123 更新时间:2023-11-30 06:35:32 26 4
gpt4 key购买 nike

我有以下代码。唯一的问题是我们通过一个 checkstyle 程序运行它,它出现了错误 Cyclomatic Complexity is 11 (max allowed is 10)。我想知道如何删除其中一个 if 语句,使其做同样的事情并让程序通过测试。

 /**
* Check if there is a winner on the board
* @return the winner if BLANK there is no winner
**/

public char checkWinner(){
this.winner = BLANK;
int totalTiles = GRIDSIZE*GRIDSIZE;

//Check if the game has a win
for (int i=0; i < GRIDSIZE; i++) {

if((grid[i][0] == grid[i][1]) && (grid[i][1] == grid[i][2])){
winner = grid[i][0];
return winner;
}
if((grid[0][i] == grid[1][i]) && (grid[1][i] == grid[2][i])){
winner = grid[0][i];
return winner;
}

}

if((grid[0][0] == grid[1][1]) && (grid[1][1] == grid[2][2])){
winner = grid[0][0];
return winner;
}

if((grid[0][2] == grid[1][1]) && (grid[1][1] == grid[2][0])){
winner = grid[0][2];
return winner;
}
//Check if the game is a tie

if (movesMade == totalTiles){
winner = TIE;
}
return winner;
}

最佳答案

我不知道检查器是如何工作的,但是这个怎么样:

if(((grid[0][0] == grid[1][1]) && (grid[1][1] == grid[2][2])) || 
((grid[0][2] == grid[1][1]) && (grid[1][1] == grid[2][0]))) {
winner = grid[1][1];
return winner;
}

如果这确实有效,当然具有讽刺意味的是,这似乎比您的代码可读性差一些。

关于java - 如何删除其中一个 if 语句并缩短代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6002720/

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