java - 从方法返回二维数组

标签 java arrays

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

我尝试创建一个具有相同名称的新数组,但它说它已经在范围内定义。我也尝试过只执行 (returnplane;) ,但由于数据类型不兼容,这不起作用。我也尝试过(返回平面[][];),但这也不起作用。

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;
        }
}

我正在尝试返回要在另一个函数中使用的数组,我将在其中修改它。

最佳答案

您必须将返回类型更改为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;

        }
    }

关于java - 从方法返回二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58532147/

相关文章:

java - AdMob 奖励视频广告的静态奖励金额

java - ZK如何在不点击任何按钮的情况下自动关闭弹出窗口?

java - 是否有必要从 Platform MBean Server 注销 MBean?

javascript - angularjs 二维数组 ng-repeat 无法正常工作

javascript - 从 double 'for' 循环中获取所有出现的值的索引

java - 使用 eclipse 在已安装的 Glassfish 上调试 Maven Web 应用程序

java - 四舍五入到最接近的 4(简单数学)

c# - LINQ 查询字符串[] 按多个匿名列分组

arrays - 每个术语出现的次数

arrays - 循环遍历不同长度的数组 Swift