Reputation: 19
Hi was hoping for some help with the logic behind reading in values for a tic tac toe game I'm building.
Upvotes: 0
Views: 420
Reputation: 54148
You have just to set a default value at start like :
int row = 0, column;
Or write another whileLoop to prevent this
Next to that, there is easier way for your assignement of row
(and be careful car you compare a String
to a char
, on my computer it didn't work ):
1. Compare the first letter of the answer (or .equals("a")
):
if (string.charAt(0)=='a')
row = 0;
if (string.charAt(0)=='b')
row = 1;
if (string.charAt(0)=='c')
row = 2;
2. Make a switch case because you compare always the same thing :
switch(string.charAt(0)){
case 'a':
row=0;
break;
case 'b':
row=1;
break;
case 'c':
row=2;
break;
}
3. Use their ASCII value :
row = string.charAt(0)-97;
So :
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
And be careful because if your inBounds()
is well-implemented : it will return true if the coordinates are correct but the while loop will continue if the condition is true and you need that it loops when coordinates are NOT correct, so you need to have !inBounds()
Upvotes: 1