我刚刚开始自学java,没有任何编程经验,我刚刚完成了Udacity的函数编程课程。在将Tic Tac Toe游戏作为最终项目时,我需要编写一个函数来检查赢家或领带。游戏被表示为一个二维数组,其他所有内容都已经给出;我唯一的工作是编码checkGameWinner函数。我已经完成了代码并使其运行。但在充分了解Java的利益,我想问下:为什么这只适用于这里的return语句?
public String checkGameWinner(char [][]grid){
String result = "None";
//Student code goes here ...
if(grid[1][1]=='x' && grid[1][0]=='x'&& grid[1][2]=='x'){
result = "X wins";
}
else if(grid[1][1]=='x' && grid[0][1]=='x'&& grid[2][1]=='x'){
result = "X wins";
}
else if(grid[1][1]=='x' && grid[0][0]=='x' && grid[2][2]=='x'){
result = "X wins";
}
else if(grid[1][1]=='x' && grid[0][2]=='x' && grid[2][0]=='x'){
result = "X wins";
}
else if(grid[0][0]=='x' && grid[1][0]=='x' && grid[2][0]=='x'){
result = "X wins";
}
else if(grid[2][0]=='x' && grid[2][1]=='x' && grid[2][2]=='x'){
result = "X wins";
}
else if(grid[0][2]=='x' && grid[1][2]=='x' && grid[2][2]=='x'){
result = "X wins";
}
else if(grid[0][0]=='x' && grid[0][1]=='x' && grid[0][2]=='x'){
result = "X wins";
}
else if(grid[1][1]=='o' && grid[1][0]=='o'&& grid[1][2]=='o'){
result = "O wins";
}
else if(grid[1][1]=='o' && grid[0][1]=='o'&& grid[2][1]=='o'){
result = "O wins";
}
else if(grid[1][1]=='o' && grid[0][0]=='o' && grid[2][2]=='o'){
result = "O wins";
}
else if(grid[1][1]=='o' && grid[0][2]=='o' && grid[2][0]=='o'){
result = "O wins";
}
else if(grid[0][0]=='o' && grid[1][0]=='o' && grid[2][0]=='o'){
result = "O wins";
}
else if(grid[2][0]=='o' && grid[2][1]=='o' && grid[2][2]=='o'){
result = "O wins";
}
else if(grid[0][2]=='o' && grid[1][2]=='o' && grid[2][2]=='o'){
result = "O wins";
}
else if(grid[0][0]=='o' && grid[0][1]=='o' && grid[0][2]=='o'){
result = "O wins";
}
else {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (grid[i][j] == '-') {
result = "None";
return result;
} else {
result = "Tie";
}
}
}
}
return result;
}
我的逻辑是,我会首先检查所有16个不同的获胜组合,然后检查是否有任何阵列中的细胞使用for循环为空(如果它们是函数返回“None”并且游戏继续)。最后,如果没有获胜组合并且没有空白空间,那么这场比赛是平局,我把它作为最后一个陈述。我发现为了让上面的代码按预期工作,我需要在double for循环(检查空白空间)中的if语句之后立即包含一个额外的return语句。如果没有添加这个回报,游戏将结束并在不正确的时刻被宣布为Tie,即使空的空间可用。我的问题是为什么这个回报是必要的?如果for循环中的if语句的布尔值为true(即有任何空格),则不应将变量“result”更新为“none”,并且会跳过后面的else语句,因此退出for循环,然后在代码的最后返回最后的回报?我已经读过,通常你不想在任何一个函数中返回多于一个返回值,但我不确定这是多么真实。我希望这是可以理解的,如果任何人有任何见解或帮助,他们可以给这个开始的程序员会非常感激。谢谢。附:空格由' - '字符表示。
@JoPeyper我看到两个。 – shmosel
你是对的,显然在Mac上的代码段滚动和铬喜欢隐藏滚动条。 –
你的逻辑不正确。事实上,一个特定的项目不是空的不会使它成为一条平行线。它只能工作,因为返回语句一找到空的空间就会使循环短路返回“无”。 – shmosel