【发布时间】:2017-02-15 18:35:18
【问题描述】:
我想干掉这段代码:
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。
【问题讨论】:
-
您可以返回您的新方法 -
return myMethod() -
哇,谢谢!没想到。
-
请查看更新。