Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何打印另一个类的数组?_Java_Arrays - Fatal编程技术网

Java 如何打印另一个类的数组?

Java 如何打印另一个类的数组?,java,arrays,Java,Arrays,我已经在公共类flights中创建了一个包含航班目的地的数组,现在我想使用公共类customers中的方法打印该数组。但由于某种原因,数组总是打印为null,我不能忘记我的错误 主要类别: 公共类主{ 公共静态void main(字符串[]args){ 航班=新航班(); 客户=新客户(); flight.createExampleData(); customer.output(); } } 公务舱航班: 公共舱航班{ 公共字符串[]目的地=新字符串[2000]; public void cr

我已经在公共类flights中创建了一个包含航班目的地的数组,现在我想使用公共类customers中的方法打印该数组。但由于某种原因,数组总是打印为null,我不能忘记我的错误

主要类别:

公共类主{
公共静态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
数组。