java构造函数无法设置从其他类获取的数据
说来话长,我不知道如何将jet数据jetid
和currentLocation
加载到j
。感谢您的帮助。如果我把事情提到错误的地方,我先道歉。多谢各位
public class Corporation {
public Jet[] jets = new Jet[14];
public Corporation()//RUN A CONSTRUCTOR TO CREATE 14 NEW JETS, IN DIFFERENT LOCATIONS
{
//create 14 new jets
for(int i =0; i < jets.length; i++)
{
//make a new jet here
Jet j = new Jet();
j.jetid =
}
}
}
第二个类是我试图从中提取的jetid
和currentLocation
是:
public class Jet {
public int jetid;
public Delivery deliveryArray[];
public String currentLocation; //where it's currently sitting
public Jet()
{
int random = (int)(Math.random()*10000);
this.jetid = random;
this.currentLocation = setCurrentLocation();
System.out.println("NEW JET IS ONLINE WITH JET ID: " + this.jetid + " AT LOCATION " + this.currentLocation);
}
private String setCurrentLocation()
{
//set up a random # that determines which city the plane is based in
double random = (Math.random());
String location = " ";
if(random < .1 && random > 0)
location = "PHX";
else if(random > .1 && random < .2)
location = "SAN";
else if(random > .2 && random <.3)
location = "LAX";
else if(random > .3 && random < .4)
location = "POR";
else if(random > .4 && random < .5)
location = "SEA";
else if(random > .5 && random <.6)
location = "SAF";
else
location = "DAL";
return location;
}
}
# 1 楼答案
谢谢大家的意见。抛开其他问题不谈,我在发布这个问题后不久就解决了这个代码:
从那时起,我就能够解决所有其他问题。再次感谢大家的投入
# 2 楼答案
您需要将变量传递给jet类构造函数
# 3 楼答案
Corporate对象将有一个数组,其中包含对Jet对象的14个引用
# 4 楼答案
您可能希望通过构造函数传递内容:
现在,您可以在公司课程中编写以下内容:
那
randomLocation
只是Jet类中旧的setCurrentLocation
方法。您应该重命名它并将其移动到您的Corporation类中,因为Corporation现在负责创建随机位置。或者,您可以将其重命名,并将其保留在Jet中,并将其公开为静态,您可以只在两行代码中实现它:然后按如下方式调用它:
# 5 楼答案
我想,我不确定你的构造器会出现什么错误:
如果在Corporate类中声明了一个局部
j[]
,则应该是以下内容另一个错误是
j.jetid =
。但是您不需要设置它,因为它已经在Jet
构造函数中设置为this.jetid = random;
。每次在Jet j[i] = new Jet();
中实例化新的Jet
时发生# 6 楼答案
该代码似乎创建了14架飞机,所有这些飞机都初始化了自己的数据(例如,它们已经拥有jetId和当前位置)。数据已经存在,公司不需要设置
如果你想让公司创建它,那么创建一个新的构造函数Jet(int-jetId,String-currentLocation),然后你就可以将数据传入