gpt4 book ai didi

java - 从方法返回二维数组

转载 作者:行者123 更新时间:2023-12-01 22:34:51 25 4
gpt4 key购买 nike

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

我尝试创建一个具有相同名称的新数组,但它说它已经在范围内定义。我也尝试过只执行 (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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com