gpt4 book ai didi

java - 我可以让方法为调用方方法返回吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:37:13 24 4
gpt4 key购买 nike

我想干掉这段代码:

YourConsultant.GameState gameState() {

for (int i = 0; i < 3; i++) {
// an 'xxx' column returns 'x', an 'ooo' returns 'o', a mixed row returns '0'
char c = areTheSame(board[i][0], board[i][1], board[i][2]);
if (c == 'x') {return YourConsultant.GameState.WON_BY_X;}
else if (c == 'o') {return YourConsultant.GameState.WON_BY_O;}
}

for (int i = 0; i < 3; i++) {
char c = areTheSame(board[0][i], board[1][i], board[2][i]);
if (c == 'x') {return YourConsultant.GameState.WON_BY_X;}
else if (c == 'o') {return YourConsultant.GameState.WON_BY_O;}
}

{
char c = areTheSame(board[0][0], board[1][1], board[2][2]);
if (c == 'x') {return YourConsultant.GameState.WON_BY_X;}
else if (c == 'o') {return YourConsultant.GameState.WON_BY_O;}
}

{
char c = areTheSame(board[0][2], board[1][1], board[2][0]);
if (c == 'x') {return YourConsultant.GameState.WON_BY_X;}
else if (c == 'o') {return YourConsultant.GameState.WON_BY_O;}
}

...
}

为此,我想编写一个简短的方法来执行此操作:

        if (c == 'x') {return YourConsultant.GameState.WON_BY_X;}
else if (c == 'o') {return YourConsultant.GameState.WON_BY_O;}

但这会使新方法返回。我想我不能做类似 super.return 的事情?我可以再次检查返回值,但这不会使我的代码变干。你有什么建议? (对不起,如果之前有人问过,我发现这很难搜索)

更新:我不能简单地传递值,因为如果 areTheSame == 0 那么我不应该返回(还)。

更新 2:我修改了代码,将每两行替换为:

        if (c == 'x' || c == 'o')  return declareWinner(c);

它工作正常,而且效果相同。仍然有一些重复,但 IMO 好多了。

最佳答案

不,方法不能为其调用者执行返回,但调用者可以直接返回被调用方法返回的值。但是,这似乎不会满足您的目的,因为您只想有条件地返回。

我会通过更深层次的改变来解决这个问题。请注意您的四个节有多相似:不仅仅是有条件的返回有点湿。您要执行的测试很少,足以被枚举,因此您可以按照以下思路考虑一些事情:

private final static int[][][] TRIPLES = new int[][][] {
{ {0, 0}, {0, 1}, {0, 2} },
{ {1, 0}, {1, 1}, {1, 2} },
{ {2, 0}, {2, 1}, {2, 2} },
{ {0, 0}, {1, 0}, {2, 0} },
{ {0, 1}, {1, 1}, {2, 1} },
{ {0, 2}, {1, 2}, {2, 2} },
{ {0, 0}, {1, 1}, {2, 2} },
{ {0, 2}, {1, 1}, {2, 0} },
};

YourConsultant.GameState gameState() {

for (int i = 0; i < TRIPLES.length; i++) {
char c = areTheSame(
board[TRIPLES[i][0][0]][TRIPLES[i][0][1]],
board[TRIPLES[i][1][0]][TRIPLES[i][1][1]],
board[TRIPLES[i][2][0]][TRIPLES[i][2][1]]
);
if (c == 'x') {
return YourConsultant.GameState.WON_BY_X;
} else if (c == 'o') {
return YourConsultant.GameState.WON_BY_O;
}
}

return YourConsultant.GameState.NO_WINNER;
}

关于java - 我可以让方法为调用方方法返回吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39905747/

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