首页 > 解决方案 > 检查“Max-Out”游戏的有效二维数组大小

问题描述

我设置了这个最大输出游戏板。它是一个 6 x 6 矩阵,使用由用户输入组成的数组。用户输入由空格分隔的 36 个数字,矩阵就建立起来了。我需要检查以确保每个数组的长度为 6 个整数。我可以通过使用 board.length 来确认它们何时出现,但是当我故意输入太多时,它似乎只是忽略了额外的,如果我输入太少,我会得到非常奇怪的输出。

有些代码是我的教授预先编写的,所以我对内部工作原理并不完全熟悉。

我通过将长度相加来打印出总整数(36),但是当我输入太多整数时,它仍然给我“正确”的大小。我猜它是因为我的循环在 6 处停止,所以它可能只是忽略了额外内容。如果整数太多,我试图让它打印“大东西”,但它没有发生。

这是主要部分,我相信它具有所有相关代码

public class MaxOut {

    public static void main(String[] args) {
        final int ROWS = 6;
        final int COLS = 6;

        Scanner s = new Scanner(System.in);
        System.out.println("Enter the matrix (36 numbers)");
        for (int i = 0; i <= 6; i++) {
            int[][] board = new int[ROWS][COLS];
            for (int r = 0; r < ROWS; r++)
                for (int c = 0; c < COLS; c++)
                    board[r][c] = s.nextInt();
            if((board[0].length + board[1].length+ board[2].length+ board[3].length+ board[4].length+ board[5].length)>36){
                System.out.println("big stuff");
            }else {
                System.out.println((board[0].length + board[1].length+ board[2].length+ board[3].length+ board[4].length+ board[5].length));
            }

            int boardTotal = 0;
            for (int r = 0; r < 6; r++)
                for (int c = 0; c < 6; c++)
                    boardTotal += board[r][c];
            System.out.println("The sum of each number in the matrix is " + boardTotal);
            for (int[] row : board)
                System.out.println(Arrays.toString(row));

            boolean[][] covered = new boolean[6][6];
            System.out.println("The maximum score for this board is " + maxVal(board, covered, 0, 0));
        }
        s.close();
    }

我想让它检查大小,以便用户必须输入 36 个整数来制作电路板。

目前,它只是忽略了额外的整数,或者当我输入太少时它给了我很多破折号和 exes(另一种方法)。

标签: javaarrayserror-handling

解决方案


您的代码有三个循环:

    for (int i = 0; i <= 6; i++) {  // 1st loop
        int[][] board = new int[ROWS][COLS];
        for (int r = 0; r < ROWS; r++)  // 2nd loop
            for (int c = 0; c < COLS; c++)  // 3rd loop
                board[r][c] = s.nextInt();

这意味着您创建和填充 6x6 矩阵的时间为 6 次。


推荐阅读