我正在寫井字遊戲,需要詢問用戶是否想再次玩(y/n)。我有遊戲的工作,我只是不知道如果用戶點擊y如何循環它,和/或如果用戶點擊n終止它。我已經嘗試了幾種不同的東西,但似乎無法找出它們中的任何一個,所以這只是我發佈的工作代碼。任何幫助將不勝感激!直到他們與回答Replay Tic Tac Toe
import java.util.Scanner;
public class Assignment7 {
public static int row, col;
public static Scanner scan = new Scanner(System.in);
public static char[][] board = new char[3][3];
public static char turn = 'X';
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
/*create for-loop
* 9 empty spots, 3x3
*/
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
board[i][j] = '_';
}
}
Play();
}
public static void Play() {
//find if game over
boolean playing = true;
PrintBoard();
while (playing) {
System.out.println("Please enter a row, then a column: ");
//make row next thing player types
row = scan.nextInt() - 1;
//same with column
col = scan.nextInt() - 1;
board[row][col] = turn;
if (GameOver(row, col)) {
playing = false;
System.out.println("Game over! Player " + turn + " wins!");
}
PrintBoard();
//switch players after entries
if (turn == 'X') {
turn = 'O';
} else {
turn = 'X';
}
}
}
public static void PrintBoard() {
for (int i = 0; i < 3; i++) {
System.out.println();
for (int j = 0; j < 3; j++) {
//get dividers on left
if (j == 0) {
System.out.print("| ");
}
// get dividers in all
System.out.print(board[i][j] + " | ");
}
}
//enter space after board
System.out.println();
}
public static boolean GameOver(int rMove, int cMove) {
// Check perpendicular victory
if (board[0][cMove] == board[1][cMove]
&& board[0][cMove] == board[2][cMove]) {
return true;
}
if (board[rMove][0] == board[rMove][1]
&& board[rMove][0] == board[rMove][2]) {
return true;
}
// Check diagonal victory
if (board[0][0] == board[1][1] && board[0][0] == board[2][2]
&& board[1][1] != '_') {
return true;
}
return false;
}
}
'do {...} while(「y」.equalsIgnoreCase(input));'? – MadProgrammer
你有什麼嘗試?發生了什麼?你只向我們展示遊戲的代碼,你說的已經有效,那麼展示它的意義何在?告訴我們你是如何試圖詢問用戶他是否想再玩一次。 – Robert