我在同一个项目中完成了(几乎)完全相同的数组返回,并且编译了一个类(PlayerArray
)但是由于某些原因我尝试在my({{1)中返回一个数组它给了我错误“Planet
”,但我不明白为什么会这样,我的意思是该方法返回一个数组,它确实返回一个数组?如果有人可以解释这些差异以及为什么一个人工作而另一个人抱怨“不兼容的类型”那么那就太棒了。谢谢!这是我的一些代码。
这是我的发射器。
Incompatible Types
播放器阵列波纹管工作..
public class Launcher
{
private static Planet myTest;
private static PlanetInfo myPlanetInfo;
private static PlanetInfo[] planetArray;
private static Player[] arr; //NEED THIS FOR arr = myArray.getPlayerArray(); to work..
public static void main(String[] args)
{
Planet myPlanetArray = new Planet();
PlayerArray myArray = new PlayerArray();
myPlanetArray.getPlanetArray();
myArray.getPlayerArray();
planetArray = myPlanetArray.returnCost();/////////////////////THIS IS THE BROKEN LINE
arr = myArray.getPlayerArray(); //holy moses this worked...
System.out.println("player 1's ID: " + arr[0].viewID());
System.out.println("player 1's balance: " + arr[0].viewBalance());
arr[0].playerGo();
}
}
这里是不会编译的类...
public class PlayerArray
{
Scanner scan = new Scanner(System.in);
private int numbHuman;
private Player[] arr;
private String[] userName;
private int[] userID;
private int startingMoney;
private int startingPosition;
private int b;
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];
userName = new String[numbHuman];
userID = new int[numbHuman];
startingMoney = 1500;
startingPosition = 0;
b=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();
arr[i] = new Player(userName[i],startingMoney,userID[i],startingPosition);
b++;
}
}
public int viewNumbHuman()
{
return numbHuman;
}
public Player[] getPlayerArray()
{
return arr; //WORKS HERE...
}
}
答案 0 :(得分:1)
字段planetArray
以
private static Planet[] planetArray;
并且您尝试在带签名
的方法中返回它public PlanetInfo[] getPlanetArray()
你的方法
public void Planets()
有一个你期望的类型的局部变量,但这与getPlanetArray
方法无关。
Planets
方法也是一个令人困惑的方法,因为看起来你可能打算创建一个构造函数,但给它一个错误的签名作为构造函数并在其中实例化Planets
对象