【问题标题】:Check for valid 2D array size for 'Max-Out' game检查“Max-Out”游戏的有效二维数组大小
【发布时间】:2019-03-27 19:57:46
【问题描述】:

我设置了这个最大输出游戏板。它是一个 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(另一种方法)。

【问题讨论】:

    标签: java arrays error-handling


    【解决方案1】:

    你的代码有三个循环:

        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 次。

    【讨论】:

    • 我移动了 int[][] board = new int[ROWS][COLS];现在到主第一个循环之外。我仍然不确定是否检查用户输入了正确数量的整数
    • 问题仍然存在 - 您仍然有 三个 循环,这意味着您正在进行 6x6x6 处理。您需要删除一个循环。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-21
    • 1970-01-01
    • 1970-01-01
    • 2016-06-09
    • 1970-01-01
    • 2011-02-27
    • 2021-01-12
    相关资源
    最近更新 更多