目前,我有一个用java编写的简单井字程序的工作代码。正如你将在下面看到的,唯一的问题是当我的电路板被显示时,空字符(\ u0000)被打印而不是空白。如何在我的Java TicTacToe程序中将空字符变成空白字符?
我的教授告诉我们要编写这个程序,以便检测出零空格,并用X或O填充它们,我这样做。
现在,我希望能够将空字符从00显示为只是空格,因为格式不正确,否则。
我已经试过简单地擦除'\ u0000'字符并用''字符替换它,但是我的电路板根本没有显示出来。任何帮助表示赞赏!
import java.util.Scanner;
public class TicTacToe
{
public static void main(String[] args)
{
char[][] board = new char[3][3];
while (true) {
makeCompMove(board, 'X');
displayBoard(board);
if(isWon('X', board)) {
System.out.println("\n\nComputer won!");
System.exit(1);
}
else if (isDraw(board)) {
System.out.println("\n\nDraw Game! No winner");
System.exit(2);
}
makeAMove(board, 'O');
displayBoard(board);
if (isWon('O', board)) {
System.out.println("\n\nPlayer won!");
System.exit(3);
}
else if (isDraw(board)) {
System.out.println("\n\nDraw Game! No winner");
System.exit(4);
}
}
}
public static void displayBoard(char[][] board)
{
for(int k = 0; k < 3; k++)
{
for(int i = 0; i < 28; i++)
{
System.out.print("-");
}
System.out.println();
for(int j = 0; j < 3; j++)
{
System.out.print("|" + " " + board[k][j] + " ");
}
System.out.println("|");
}
for(int i = 0; i < 28; i++)
{
System.out.print("-");
}
}
public static void makeAMove(char[][] board, char o)
{
Scanner input = new Scanner(System.in);
while(true)
{
System.out.print("\n\nYour turn. Enter a row and col(0,1 or 2): ");
int row = input.nextInt();
int col = input.nextInt();
if(row > 2 || row < 0 || col > 2 || col < 0)
{
System.out.println("Incorrect Input. Try Again!");
continue;
}
if(board[row][col] == '\u0000')
{
System.out.print("\n You (O) have made your move...\n\n");
board[row][col] = 'O';
break;
}
else
System.out.println("Incorrect Input. Try Again!");
}
}
public static void makeCompMove(char[][] board, char x)
{
System.out.println();
System.out.println();
System.out.print("Computer (X) has made his move...\n");
while(true)
{
int row = (int)(Math.random()*3);
int col = (int)(Math.random()*3);
if(board[row][col] == '\u0000')
{
board[row][col] = x;
break;
}
}
System.out.println();
}
public static boolean isDraw(char[][] board)
{
for(int row = 0; row < 3; row++)
{
for(int col = 0; col < 3; col++)
{
if(board[row][col] == '\u0000')
{
return false;
}
}
}
return true;
}
public static boolean isWon(char x, char[][] board)
{
// Check Rows
for (int i = 0; i < 3; i++)
if (x == board[i][0] && x == board[i][1] && x == board[i][2])
return true;
// Check Columns
for (int j = 0; j < 3; j++)
if (x == board[0][j] && x == board[1][j] && x == board[2][j])
return true;
// Check first diagonal
if (x == board[0][0] && x == board[1][1] && x == board[2][2])
return true;
// Check second diagonal
if (x == board[0][2] && x == board[1][1] && x == board[2][0])
return true;
return false;
}
}
Ohhhhh!非常感谢你,像一个魅力! – dmetal23