我正在尝试制作一个井字游戏,但我不知道如何更改数组
如果我这样做,它不会改变我的数组,但如果我把I换成a,把j换成b(在这里是System.out.print(matrixe[a][b]+"|");它从空白变成了X,我不知道为什么
package joc;
import java.util.Scanner;
public class jocxo {
public static char[][] matrice = new char[3][3];
public static Scanner Int = new Scanner(System.in);
public static int a;
public static int b;
public static void main(String[] args){
board();
game();
}
public static void board()
{
for(int i = 0; i<3; i++){
System.out.println();
for(int j=0; j<3; j++){
matrice[i][j] ='_';
if ( j==0 )
System.out.print("|");
System.out.print(matrice[i][j] + "|");
}
}
}
public static void game(){
a = Int.nextInt() - 1;
b = Int.nextInt() - 1;
if (matrice[a][b] == '_')
{
matrice[a][b] ='X';
board();
}
}
}
在获得输入后,您将再次调用board()
。看看board()
在做什么。
matrice[i][j] = '_';
您正在将matrice[a][b]
设置为X
。之后,您可以使用董事会功能打印您的董事会。但是,由于您也使用它来初始化您的板,您基本上是在重置阵列,使其仅包含_
。
您应该创建一个类似initizalize()
的方法,您的代码可以如下所示。
public static void main(String[] args) {
initialize();
board();
game();
}
public static void board() {
for (int i = 0; i < 3; i++) {
System.out.println();
for (int j = 0; j < 3; j++) {
if (j == 0)
System.out.print("|");
System.out.print(matrice[i][j] + "|");
}
}
}
private static void initialize() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
matrice[i][j] = '_';
}
}
}
public static void game() {
a = Int.nextInt() - 1;
b = Int.nextInt() - 1;
if (matrice[a][b] == '_') {
matrice[a][b] = 'X';
board();
}
}
public static char[][] matrice = new char[3][3];
public static Scanner Int = new Scanner(System.in);
public static int a;
public static int b;
public static void main(String[] args){
initBoard();
game();
displayBoard();
}
public static void initBoard(){
for(int i = 0; i<3; i++){
System.out.println();
for(int j=0; j<3; j++){
matrice[i][j] ='_';
if ( j==0 )
System.out.print("|");
System.out.print(matrice[i][j] + "|");
}
}
}// board close
public static void displayBoard(){
for(int i = 0; i<3; i++){
System.out.println();
for(int j=0; j<3; j++){
if ( j==0 )
System.out.print("|");
System.out.print(matrice[i][j] + "|");
}
}
}// board close
public static void game(){
a = Int.nextInt() - 1;
b = Int.nextInt() - 1;
System.out.println(matrice[a][b] == '_');
if (matrice[a][b] == '_')
{ matrice[a][b] ='X';
}
}// game close.