我想干掉这段代码:
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;}
来源:https://www.icode9.com/content-4-561851.html
联系客服