首页 > 解决方案 > 我将如何着手将此代码转换为手动将参数提供给该方法并返回一个 2D char 数组?

问题描述

public static void tehtava7() {
    java.util.Scanner input = new java.util.Scanner(System.in);

    System.out.println("Give height");
    int height = input.nextInt();

    char[][] array = new char[height][height];

    for (int row = 0; row < array.length; row++) {
        for (int col = 0; col < array[row].length; col++) {
            if (row == col || col == 0 || col == height - 1) {
                array[row][col] = 'X';
            } else {
                array[row][col] = ' ';
            }
        }
    }
    printTwoDimCharArray(array);
}

public static void printTwoDimCharArray(char[][] myarray) {
    for (int i = 0; i < myarray.length; i++) {
        for (int j = 0; j < myarray[i].length; j++) {
            System.out.print(myarray[i][j]);
        }
        System.out.println();
    }
}

public static void main(String[] args) {
    tehtava7();
}

我需要手动将参数提供给该方法,并根据height * height我提供给该方法的值返回一个 2D 字符数组。它还应该N根据给定的参数打印相同的形状。我该怎么做呢?所以基本上我不会问用户高度,而是手动导入。

标签: javaarrayschar

解决方案


我不会问用户,height而是手动导入。

首先,我建议您将height其视为函数的参数。

前:

    public static void tehtava7() {
        java.util.Scanner input = new java.util.Scanner(System.in);

        System.out.println("Give height");
        int height = input.nextInt();

        char [][] array = new char[height][height];
        // ...

后:

    public static void tehtava7(int height) {
        //                      ^--- NOTICE: NEW PARAMETER

        char [][] array = new char[height][height];
        // ...

接下来,确定您希望如何“导入”它。

使用高度数组导入:

前:

    public static void main(String[] args) {
        tehtava7();
    }

后:

    public static void main(String[] args) {
        int[] heights = new int[] { 2, 4, 6, 8, 10 }; // heights to import
        for(int height : heights) {
            tehtava7(height);
            //       ^---- NOTICE: LOOP AGAINST PARAMETERS
        }
    }

...或直接从命令行导入参数:

   public static void main(String[] args) {
        // args = command line options

        // loop over command line options, convert to integer
        int[] heights = new int[args.length];
        for(int i = 0; i < args.length; ++i) {
            heights[i] = Integer.parseInt(args[i]);
        }

        for(int height : heights) {
            tehtava7(height);
            //       ^---- NOTICE: LOOP AGAINST PARAMETERS
        }
    }
java MyClass 2 4 6 8

输出:

XX
XX
X  X
XX X
X XX
X  X
X    X
XX   X
X X  X
X  X X
X   XX
X    X
X      X
XX     X
X X    X
X  X   X
X   X  X
X    X X
X     XX
X      X

推荐阅读