[英]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.createExampleData
但output
方法使用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.