繁体   English   中英

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

[英]How do I print the array of another class?

我在公共班级航班中创建了一个包含航班目的地的数组,现在我想使用公共班级客户中的方法打印出该数组。 但出于某种原因,数组总是打印为空值,我很遗憾不能犯我的错误。

主类:

public class Main {
    public static void main(String[] args) {
        flight flight = new flight();
        customer customer = new customer();
        flight.createExampleData();
        customer.output();
    }
}

公共舱航班:

public class flight{
    public String[] destination = new String[2000];
    public void createExampleData(){
        this.destination[1] = "Paris";
        this.destination[2] = "Geneve";
        this.destination[3] = "Florida";
    }
}

公开课客户:

public class customer{
    flight flight = new flight();
    public int i;
    public void output() {
        this.i=1;
        while (i<4){
            System.out.println("Flightnumber: " + this.i);
            System.out.println("Destination: " + flight.destination[this.i]);
            System.out.println("");
            this.i++;
        }
    }
}

(由于在此简化版程序中看不到的原因,我无法将打印内容放入航班类中)

方法 createExampleData 后方法 outpout 的结果:


航班号:1

目的地:空

航班号:2

目的地:空

航班号:3

目的地:空


谢谢您的帮助

也许您还没有在customers类中执行createExampleData()函数?

您正在使用两个不同的flight对象,一个在main创建,一个在您的customer类中创建,然后您在 main 中创建的实例上调用flight.createExampleDataoutput方法使用customer对象中的一个,因此该数组中的一个是从未给出任何值,因此输出中为 null。

我现在的建议是在customer公开flight变量

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();
    }
}

一个更好的解决方案可能是一个getFlight()方法添加到customer ,而不是和保持私有变量。

    flight.createExampleData();

当您调用它时,会执行 Flight 类中的 createExampleData 方法。

    customer.output();

当您在 Customer 类中调用此输出方法时执行。

您的代码中 Flight 和 Customer 类之间没有关系。 因此,客户对象的输出方法不会知道 Flight 类的 createExampleData 中发生了什么。

你可以这样做

  String [] flightDestinations = flight.createExampleData();
  customer.output(flightDestinations);

您必须更改客户类中的输出方法才能使用此字符串数组并打印其详细信息。 此外, createExampleData 的返回类型应该是 String [] 才能工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM