我正在尝试制作井字游戏,但我不知道如何更改数组
如果我这样做,它不会改变我的数组,但如果我将 i 替换为 a,将 j 替换为 b( 此处 System.out.print(matrice[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();
}
}
关于java - 2段代码有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33384891/