Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/338.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_Class - Fatal编程技术网

Java 如何在太多的类之间传递值?

Java 如何在太多的类之间传递值?,java,class,Java,Class,我有三个包含getter、setter和constructor的类(包含Main类)。在一个名为frame的类中,我设置了两个私有整数行和列,并在Main类中请求用户输入。之后,我想通过这个整数行和列来设置名为Flight的类中数组的大小。我应该怎么做 我试图在飞行课上创建一个扫描仪对象和一个来自飞机的对象,但我意识到我要求另一个不同的值,我已经在Main中设置了这个值。有没有办法从main中获取值行和列,并将其放入Flight类中 飞机等级: public class Airplane {

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

我试图在飞行课上创建一个扫描仪对象和一个来自飞机的对象,但我意识到我要求另一个不同的值,我已经在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命名约定。字段/变量名称在Java中以大写形式出现。总是。有时候你这样做对你的读者真的没有帮助,但你还是用大写。@CyrilCherian我的代码是基于某个描述的,它没有像要求其他类那样说明扩展。@CyrilCherian老实说:一点也没有。飞行是一种概念,一种想法,一种表示将要发生的“事件”的东西。飞机不是这样的。而且仅仅使用继承来避免代码重复很少是个好主意。这可能是正确的@GhostCat,我对此一无所知。我可以回答说,
飞机
只是定义模型,而不是具体的地点;)感谢您的输入,这绝对是最好的方式,可以在需要时分配飞机,并确保两架飞机不用于不同的航班(顺便说一句,我总是喜欢“挑剔”的评论!!)欢迎@MikePanrs。我没有试图用最好的方法解决这个问题。我主要发布这个答案,因为在评论中解释起来很复杂。如果您对此有任何疑问(离原始问题不远),请不要犹豫。