如何在 java 的二维数组中插入一个值

How to insert a value in 2D array in java

如何使用 2D 数组填充 3x3 矩阵,以便用户选择什么 他们要输入字符串值的数组的位置?

仓位格式为:(Row Number, Column Number)

例如:

Person 1, please pick where to place an X: (0,1)
Person 2, please pick where to place an O: (0,2)

这是我的:

import java.util.Scanner;

public class idk {
    public static void main(String[] args)

    {
        int i;
        int j;
        int arr[][] = new int[3][3];

        // Getting user input
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a number: ");
        for (i = 0; i < 3; i++) {
            for (j = 0; j < 3; j++) {
                arr[i][j] = input.nextInt();
             }

        }

        // Outputting the user input
        System.out.println("The output is: ");
        for (i = 0; i < 3; i++) {
            for (j = 0; j < 3; j++) {
                System.out.printf("%d ", arr[i][j]);
            }
        }
    }    
}

简直

arr[Row Number][Column Number]=X;

例如

arr[0][1]=X;

arr[1][0]=O;

但是因为它是一个 int 数组,所以你不能在其中放置字符串,即 "O" 和 "X"。

尝试将其设为字符串数组

像下面这样的内容包含您想要的大部分内容,错误处理除外。输入是数字,space(或任何白色space),最后是另一个数字。输入数字是 1 到 3(含),这是正常人所期望的。

import java.util.Scanner;

public class TicTacToe {

    char board[][] = new char[][]{{'-','-','-'},{'-','-','-'},{'-','-','-'}};

    public static void main(String[] args) {

        TicTacToe ttt = new TicTacToe();
        ttt.run();
    }

    public void run() {
        Scanner input  = new Scanner(System.in);
        int row = -1, col = -1;//just to initialize 
        char symbol = 'o';

        while (true) {
            symbol = (symbol == 'x')?'o':'x';
            boolean error = false;

            System.out.println("Enter a number: ");
            if (input.hasNext()) {
                row = input.nextInt();
                System.out.println("row: " + row);
            } else {
                error = true;
            }
            if (input.hasNext()) {
                col = input.nextInt();
                System.out.println("col: " + col);
            } else {
                error = true;
            }
            if (!error) {
                board[row - 1][col - 1] = symbol;
            }else{
                System.out.println("an error has occurred");
            }
            input.reset();
            this.drawBoard();
        }
    }

    public void drawBoard() {
        System.out.println("The output is: ");
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                System.out.printf("%c ", board[i][j]);
            }
            System.out.println();
        }
        System.out.println();
    }
}

如果你查找 Scanner,你会看到一个使用正则表达式解析的示例,我更喜欢这种方法,因为使用正则表达式你可以一次验证整个字符串,但因为这不在问题中代码我没有用那个方法。