您只需在开始时设置默认值,如:
int row = 0, column;或者写另一个whileLoop来防止这种情况
接下来,您可以更轻松地分配row(并且小心驾驶您将String与char进行比较,在我的计算机上它不起作用):
1.比较答案的第一个字母(或.equals("a")):
if (string.charAt(0)=='a')
row = 0;
if (string.charAt(0)=='b')
row = 1;
if (string.charAt(0)=='c')
row = 2;2.制作一个开关盒,因为你总是比较相同的东西:
switch(string.charAt(0)){
case 'a':
row=0;
break;
case 'b':
row=1;
break;
case 'c':
row=2;
break;
}3.使用其ASCII值:
row = string.charAt(0)-97;
所以:
public void askPlayer(char player) {
Scanner instruction = new Scanner(System.in);
int row, column;
do {
System.out.printf("Player %s please enter an instruction (a-c): ", player);
String string = instruction.next();
row = string.charAt(0)-97;
System.out.printf("Player %s please enter a column (1-3): ", player);
column = instruction.nextInt();
} while (!inBounds(row, column));
makeMove(player, row, column - 1);
} // end of ask player method并且要小心,因为如果您的inBounds()已经很好地实现了:如果坐标正确,它将返回true但是如果条件为真则while循环将继续,并且当坐标不正确时你需要它循环,所以你需要有!inBounds()