从方法返回二维数组

时间:2019-10-23 23:21:26

标签: java arrays

我正在尝试从类内部的函数返回二维数组。我不想在函数内部创建新数组,因为我想返回传递给函数的相同数组。

我尝试用相同的名称创建一个新数组,但是它说它已经在范围内定义了。我还尝试过做(返回平面;),因为数据类型不兼容,该方法不起作用。我也试过了(return plane [] [];),但这也不起作用。

public class Airplane {
    private String maxSeats; //used for constructor
    private char[][] plane = new char[13][6]; //array to be passed in

 public char create(char[][] plane) {
       plane[13][6]; //this is where I'm unsure what to do
        //initialize them as '*' to start
        for (int i = 0; i <= 12; i++) {
            for ( int k = 0; k <= 5; k++) {
                 plane[i][k] = '*';
            }
return plane;
        }
}

我试图返回要在另一个函数中使用的数组,在该函数中将对其进行修改。

1 个答案:

答案 0 :(得分:0)

您必须将返回类型更改为 char [] [] ,因为您要返回二维字符数组,而不仅仅是单个字符

public class Airplane {
        private String maxSeats;
        private char[][] plane = new char[13][6];

        public char[][] create(char[][] plane) {

            // plane[13][6]; you should remove this line, it's the wrong syntax 
           //and it's unneeded since you've already declared this array

            // this is a more compact version of your nested loop
            for (int i = 0; i < 13; i++) {
                Arrays.fill(plane[i], '*'); //fills the whole array with the same value
            }

            return plane;

        }
    }