Java 如何将多维数组传递给构造函数?
我正在声明多维数组Java 如何将多维数组传递给构造函数?,java,arrays,object,multidimensional-array,parameter-passing,Java,Arrays,Object,Multidimensional Array,Parameter Passing,我正在声明多维数组propertyArray=newint[numbHuman][40] 其中,[numbHuman]是行数,[40]是列数(反之亦然)。无论如何,我在嵌套的for循环中创建了这些propertyArray,但我不确定如何将propertyArray[]]传递到player对象构造函数中。这是我的代码,如果需要,我会尽力澄清 import java.util.Scanner; import java.util.Random; public class PlayerArray {
propertyArray=newint[numbHuman][40]
其中,[numbHuman]
是行数,[40]
是列数(反之亦然)。无论如何,我在嵌套的for循环中创建了这些propertyArray,但我不确定如何将propertyArray[]]传递到player对象构造函数中。这是我的代码,如果需要,我会尽力澄清
import java.util.Scanner;
import java.util.Random;
public class PlayerArray
{
Scanner scan = new Scanner(System.in);
private int numbHuman;
private Player[] arr;
private String[] userName;
//private
private int[] testArray;
private int[][] propertyArray;
private int[] userID;
private int startingMoney;
private int startingPosition;
private int b;
private int c;
private int i;
//private int d;
public PlayerArray()
{
Scanner scan = new Scanner(System.in);
System.out.println("How many players wish to play? Values of 2 through 8 accepted.");
numbHuman = scan.nextInt();
System.out.println(numbHuman + " players selected.");
while (numbHuman < 2 || numbHuman > 8)
{
System.out.println("Invalid entry, try again.");
numbHuman = scan.nextInt();
}
arr = new Player[numbHuman];
i=0;
testArray = new int[40];
propertyArray = new int[numbHuman][40];///// WORK ON DIS
userName = new String[numbHuman];
userID = new int[numbHuman];
startingMoney = 1500;
startingPosition = 0;
b=0;
c=0;
for(int i = 0; i < arr.length; i++)
{
userID[i] = b;
System.out.println("Player " + (i + 1) + ", Please enter your first name:");
userName[i] = scan.next();
for(c = 0; c < 40; c++)
{
propertyArray[i][c] = 0;
}
arr[i] = new Player(userName[i],startingMoney,userID[i],startingPosition,propertyArray[i][c]);
b++;
}
}
您需要为每个标注指定一组方括号,例如:
public Player(String userName, int changeInMoney, int userID,
int startingPosition, int[][] propertyArray)
只需添加一对额外的括号:
public Player(String userName, int changeInMoney, int userID, int startingPosition, int[][] propertyArray)
旁注:最好不要在数组类本身中提供所有的输入提示。EDIT刚刚更新了第一个类的最后一行。很抱歉,我不小心遗漏了一小部分重要代码,它应该是arr[I]=new Player(用户名[I]、startingMoney、userID[I]、startingPosition、propertyArray[I][c])@Bolloahheffay这没什么区别,为了接受二维数组,您需要重新定义构造函数以匹配上面的原型。哦,对不起,我也这么做了,让我再次更新代码XD,它仍然无法编译,抱怨“实际参数int无法通过方法调用转换转换为int[][]”@Bolloahheffay抱歉,重新阅读您的代码行,您实际上没有传递二维数组,
propertyArray[i][c]
是单个元素(即int
)。也许你的意思是:arr[i]=newplayer(用户名[i]、startingMoney、userID[i]、startingPosition、propertyArray)代码>我的意图是给每个玩家
一个对应的数组,其中每个索引包含一个0。我开始觉得我处理问题的方法不对。。。
public Player(String userName, int changeInMoney, int userID, int startingPosition, int[][] propertyArray)