Java 构造函数可以';t设置从另一个类获取的数据
说来话长,我不知道如何将jet数据Java 构造函数可以';t设置从另一个类获取的数据,java,constructor,instance,Java,Constructor,Instance,说来话长,我不知道如何将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 { //c
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 =
}
}
}
我不确定您得到的是什么错误,我假定,您的构造函数:
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 =
}
}
public Jet(int jetid, String currentLocation)
{
this.jetid = jetid;
this.currentLocation = currentLocation;
}
另一个错误是
j.jetid=
。但是您不需要设置它,因为它已经在Jet
构造函数中设置为this.jetid=random代码>。每次在Jet j[i]=new Jet()中实例化新的Jet
时发生代码>代码似乎创建了14架飞机,所有这些飞机都初始化了自己的数据(例如,它们已经拥有jetId和当前位置)。数据已经存在,公司不需要设置它
如果您想让公司创建它,那么创建一个新的构造函数Jet(int-jetId,String-currentLocation),您可以将数据传入。公司对象将有一个数组,其中包含对Jet对象的14个引用
public class Corporation {
private Jet[] jets = new Jet[14];
// Constructor
// RUN A CONSTRUCTOR TO CREATE 14 NEW JETS, IN DIFFERENT LOCATIONS
public Corporation() {
//create 14 new jets
for (int i =0; i < jets.length; i++)
{
//make a new jet here
Jet j = new Jet();
//save the reference to array
jets[i] = j;
// more Jet intialization
j.id = ...
}
}
// accessor
public Jet [] getJets() {
...
}
}
公共类公司{
私人飞机[]喷气式飞机=新飞机[14];
//建造师
//运行一个构造器,在不同的位置创建14个新的喷射器
上市公司({
//创造14架新飞机
对于(int i=0;i
您可能希望通过构造函数传递内容:
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 =
}
}
public Jet(int jetid, String currentLocation)
{
this.jetid = jetid;
this.currentLocation = currentLocation;
}
现在,您可以在Corporate类中编写以下内容:
for(int i =0; i < jets.length; i++)
{
//make a new jet here
int randomId = (int)(Math.random()*10000);
String randomLocation = randomLocation();
jets[i] = new Jet(randomId, randomLocation);
}
然后按如下方式调用它:
String randomLocation = Jet.randomLocation();
您需要将变量传递给jet类构造函数
Jet jet = new Jet(string _jetID, string _currentLocation)
如果我正确理解了您的问题,您需要设置jetid
和currentLocation
,而不需要更改Jet
构造函数,如下所示:
public Jet(int jetid, String currentLocation)
{
this.jetid = jetid;
this.currentLocation = currentLocation;
}
谢谢大家的意见。抛开其他问题不谈,我在发布此问题后不久就解决了此代码:
Jet j = new Jet();
jets[i]=j;
从那时起,我就能够解决所有其他问题。再次感谢大家的投入您在哪里向任何构造函数传递任何内容?在哪里定义接受参数的构造函数。您需要阅读有关构造函数的教程部分。你还需要创建一个Jet数组来存储你的对象。你只有七个位置,所以你的请求在数学上是不可能的。一个更清晰的问题陈述可以帮助人们回答你的问题。我不知道你说的“将Jet数据…加载到j
”是什么意思。我假设您想在新的Jet
j
中设置这些字段,但您要加载的Jet数据到底在哪里?
Jet j = new Jet();
jets[i]=j;