在一个函数中创建数组并在另一个函数中读取它,而不使用返回语句。

4
我想在一个方法(函数?对象?顺便问一下 - 这些单词之间有什么区别?)中创建一个数组,然后在另一个方法中使用它的长度(我还将在其他地方使用它)。 我的老师告诉我不需要返回数组,因为我只是修改它的位置,所以数组并没有被销毁或者其他什么。如果我在主函数中声明,那么我就无法在获取大小输入后调整其大小(我不认为可以吧?)

有人听得懂吗?

public class Update {

public static void main(String[] args) {

    System.out.println("This program will simulate the game of Life.");

    createMatrix();

    // birthAndLive();

    printMatrix();

}

public static void createMatrix() {

    Scanner console = new Scanner(System.in);

    System.out.println("Please input the size of your board.");

    System.out.println("Rows:");
    final int rows = console.nextInt();

    System.out.println("Columns:");
    final int columns = console.nextInt();

    System.out.println("Please enter a seed:");
    final long seed = console.nextLong();

    boolean[][] board = new boolean[rows][columns];
    Random seedBool = new Random(seed);

}

public static void printMatrix() {

    for (int i = 0; i < board.length; i++) {
        for (int j = 0; j < board[i].length; j++) {
            if (board[i][j] == false)
                System.out.print(" - ");
            else
                System.out.print(" # ");
        }
        System.out.println();
    }

}

下次不要忘记添加Java标签。 - Neko
1个回答

3
您可以通过将board传递给您的打印函数来解决此问题。
class Update {
    public static void main(String[] args) {

        System.out.println("This program will simulate the game of Life.");
        createMatrix();

        // birthAndLive();

        printMatrix();

    }
    public static void createMatrix() {

        Scanner console = new Scanner(System.in);

        System.out.println("Please input the size of your board.");

        System.out.println("Rows:");
        final int rows = console.nextInt();

        System.out.println("Columns:");
        final int columns = console.nextInt();

        System.out.println("Please enter a seed:");
        final long seed = console.nextLong();

        boolean[][] board = new boolean[rows][columns];
        Random seedBool = new Random(seed);

        printMatrix(board);
    }

    public static void printMatrix(boolean[][] board) {

        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                if (board[i][j] == false)
                    System.out.print(" - ");
                else
                    System.out.print(" # ");
            }
            System.out.println();
        }

    }
}

我不确定你的老师允许你修改多少代码。如果所有函数都需要从main调用,那么你要么必须将数组创建代码放在main函数内部,要么就必须使用返回语句或类变量。


她说我们不能使用任何类级别的变量。这让我很痛苦,因为我感觉我可以用其他方法轻松地完成这个任务。 - Noah
啊,那种情况下,我认为她希望你将板子作为参数传递给你的函数。我会编辑我的帖子。 - Neko
传递板子给函数是这里的正确方法。没错。 - Louis Wasserman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接