Java 如何打印另一个类的数组?
我已经在公共类flights中创建了一个包含航班目的地的数组,现在我想使用公共类customers中的方法打印该数组。但由于某种原因,数组总是打印为null,我不能忘记我的错误 主要类别:Java 如何打印另一个类的数组?,java,arrays,Java,Arrays,我已经在公共类flights中创建了一个包含航班目的地的数组,现在我想使用公共类customers中的方法打印该数组。但由于某种原因,数组总是打印为null,我不能忘记我的错误 主要类别: 公共类主{ 公共静态void main(字符串[]args){ 航班=新航班(); 客户=新客户(); flight.createExampleData(); customer.output(); } } 公务舱航班: 公共舱航班{ 公共字符串[]目的地=新字符串[2000]; public void cr
公共类主{
公共静态void main(字符串[]args){
航班=新航班();
客户=新客户();
flight.createExampleData();
customer.output();
}
}
公务舱航班:
公共舱航班{
公共字符串[]目的地=新字符串[2000];
public void createExampleData(){
这个。目的地[1]=“巴黎”;
此.destination[2]=“Geneve”;
此.destination[3]=“Florida”;
}
}
公共类客户:
公共类客户{
航班=新航班();
公共国际一级;
公共无效输出(){
这个。i=1;
而(i可能您没有在customers
类中执行函数createExampleData()
flight.createExampleData();
调用此函数时,将执行Flight类中的createExampleData方法
customer.output();
当您在Customer类中调用此输出方法时,将执行
customer.output();
代码中Flight和Customer类之间没有关系。因此,Customer对象的输出方法不知道Flight类的createExampleData中发生了什么
你可以这样做
String [] flightDestinations = flight.createExampleData();
customer.output(flightDestinations);
您必须更改customer类中的输出方法才能使用此字符串数组并打印其详细信息。此外,createExampleData的返回类型应为string[]为此,您将使用两个不同的flight
对象,一个在main
中创建,另一个在customer
类中创建,然后调用flight。在main中创建的实例上,createExampleData
,但输出
方法使用customer
对象中的对象,因此arr其中的ay从未被赋予任何值,因此在输出中为null
我现在的建议是将客户
中的航班
变量公开
public class customer{
public flight flight = new flight();
...
}
然后将main更改为
public class Main {
public static void main(String[] args) {
customer customer = new customer();
customer.flight.createExampleData();
customer.output();
}
}
更好的解决方案可能是向customer
添加一个getFlight()方法,并将变量保持为私有。您有ankuffortic
和destination
,哪一个是正确的?请注意数组索引从0开始。要回答您的问题,您将得到null,因为您从未调用createExampleData()output()
中的
。投票以键入方式关闭1。确保调用flight.createExampleData()
.2.在这里使用循环,而不是循环。@JoakimDanielson打字错误仅出现在本文中,而不是我的代码,因为我将文章的变量名称更改为英文。我在主类中调用函数,该函数执行函数createExampleData()然后输出().但它仍然输出Null我的主类中有一个执行函数createExampleData(),然后输出()@reichenwald,我想你应该检查Joakim Danielson的答案,我同意他的说法。另外,我对行flight flight=flight flight()感到犹豫;
在customers类中,可能最好使用flight flight=new flight();
。最后,类的名称通常以大写字母开头。(它们变得更容易识别)。例如,客户或航班。非常感谢它现在可以工作了。但请您简要解释一下为什么我必须这样做,好吗?@reichenwald航班的每个实例都有自己的数组目的地
,并且由于您的输出()
方法属于customer对象,它使用同样属于customer(是成员变量)的flight
对象。因此,您需要在flight
的正确实例上调用createExampleData(),以便更新正确的destination
数组。