import java.util.Scanner;
public class TicTacToe {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
board b = new board();
while (!b.detectWin('x') && !b.detectWin('o') && !b.detectTie()) {
b.printBoard();
System.out.println("Player 1, where do you want to put an x?");
int xAnswer = input.nextInt();
b.setSpot('x', xAnswer);
b.printBoard();
System.out.println("Player 2, where do you want to put an o?");
int oAnswer = input.nextInt();
b.setSpot('o', oAnswer);
b.printBoard();
if(b.detectWin('x')) {
System.out.println("Player 1 won!");
}else if (b.detectWin('o')) {
System.out.println("Player 2 won!");
}else {
System.out.println("There was a tie.");
}
}
}
}
这是一个tic tac toe计划,这是董事会成员:
public class board {
private char[] board;
public board() {
board = new char[]
{'0', '1', '2',
'3', '4', '5',
'6', '7', '8'};
}
public void setSpot(char player, int position) {
if (board[position] == position+48) {
board[position] = player;
}else {
System.out.println("Incorrect move, turn skipped");
}
}
public boolean detectWin(char player){
if((board[0] == player && board[1] == player && board[2] == player)
|| (board[3] == player && board[4] == player && board[5] == player) ||
(board[6] == player && board[7] == player && board[8] == player) ||
(board[0] == player && board[3] == player && board[6] == player) ||
(board[1] == player && board[4] == player && board[7] == player) ||
(board[2] == player && board[5] == player && board[8] == player) ||
(board[0] == player && board[4] == player && board[8] == player) ||
(board[2] == player && board[4] == player && board[6] == player))
return true;
else
return false;
}
public boolean detectTie() {
for (int i = 0; i > board.length; i++) {
if (board[i] == i+48)
return false;
}
return true;
}
public void printBoard() {
System.out.println(board[0] + " | " +board[1] +" | " +board[2]);
System.out.println("---------");
System.out.println(board[3] + " | " + board[4] + " | " + board[5]);
System.out.println("--------");
System.out.println(board[6] + " | " + board [7] + " | " + board[8]);
}
}
它一直被终止,我无法找到原因。没有错误消息。
(帖子占位符大多为代码错误占位符,帖子大多是代码错误占位符,帖子大多是代码错误占位符,帖子大多是代码错误占位符,帖子大多是代码错误
答案 0 :(得分:0)
代码中的简单拼写错误,更改detectTie如下:
public boolean detectTie() {
for (int i = 0; i < board.length; i++) {
if (board[i] == i+48)
return false;
}
return true;
}
你应该好。你使用int i = 0;我&gt; board.length; i ++,所以我从0开始,并且这不超过板数组长度所以它从不执行循环并且只返回true,这反过来导致!b.detectTie()返回false,这意味着主while循环是从未执行过。