[英]Returning a 2-Dimensional Array from a method
我正在嘗試從 class 內部的 function 返回一個二維數組。 我不想在 function 中創建一個新數組,因為我想返回傳遞給 function 的同一個數組。
我嘗試創建一個同名的新數組,但它說它已經在 scope 中定義。 我也嘗試過 (return plane;) 由於數據類型不兼容而無法正常工作。 我也試過 (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;
}
}
我正在嘗試返回要在另一個 function 中使用的數組,我將在其中對其進行修改。
您必須將返回類型更改為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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.