java - 如何在太多类之间传递值?

标签 java class

我有三个类(包含主类),带有 getter、setter 和构造函数。在一个名为 Airplane 的类中,我设置了两个私有(private)整数行和列,并要求主类中的用户输入。之后,我想通过这个整数行和列来设置名为 Flight 的类中的数组的大小。我应该怎么做?

我尝试在 Flight 类中创建一个扫描仪对象和一个来自 Airplane 的对象,但我意识到我要求提供另一个已在 Main 中设置的不同值。有什么方法可以从 main 中获取值行和列并将其放入 Flight 类中吗?

飞机等级:

public class Airplane {
   private String code;
   private String description;
   private int rows;
   private int columns;

航类等级:

public class Flight {

private String ticketCode;
private String AirportDeparture;
private String AirportLanding;
private int Seats[][];
private String menuCode;
private int NumOfSeats;
private int NumOfTakenSeats;
private LocalDate dateOfDeparture;
private LocalTime timeOfDeparture;

主类:

 Airplane airp = new Airplane();
 System.out.println("Give a code.");
 String code = scanner.nextLine();
 airp.setCode(code);
 System.out.println("Give number of rows.");
 int rows = scanner.nextInt();
 airp.setRows(rows);
 System.out.println("Give number of columns.");
 int columns = scanner.nextInt();
 airp.setColumns(columns);
 System.out.println("Give number of business class rows.");
 int BCrows = scanner.nextInt();
 airp.setBCrows(BCrows);

最佳答案

航类与飞机相关联,因此它应该简单地引用它。

public class Flight {

    private Airplane airplane;
    private int[][] seats;

}

当您设置平面时,您将能够使用平面的值初始化数组。

public void setPlane(Airplane airplane){
    this.airplane = airplane;
    this.seats = new int[airplane.getRows()][airplane.getColumns()];
}

请注意,我使用了 setter,这可以/应该在构造函数中。

现在,我们可以争论飞机是否应该引用其航类,但这并不是真正的重点。

关于java - 如何在太多类之间传递值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56021418/

相关文章:

c++ - 不允许复制构造函数但允许从其他类型隐式复制

java - 为我的计算器小程序创建一个类

java - 为什么在解析第一个字符串数组中的数据时会抛出异常,但在跳过第一个数组时不会抛出异常?

java - LinkedList.pollLast() 抛出 NullPointerException

c++ - 是否可以引用随机类?

java - Java 中盒装类的类型转换?

c++ - 如何在前面定义的类 X 中的代码中使用后面定义的类 Y?

java - 我想借助 java 程序从 azure 监视器获取 Activity 、key-vault、nsg 流日志等日志,并将它们发送到 tcp/http 端点

java - Android Studio 调试器突出显示错误行

JavaRegEx 和复杂的长字符串