如何将某些值从一个类转移到另一个类?

时间:2019-05-09 13:32:12

标签: java class java.util.scanner composition

首先,我有3个带有getter和setter的类。在Main类中,我扫描了两个const wantedPersons = await Person.find({firstName: {$in: wantedFirstNames}}) // Also returns two matching documents 类型的变量,分别称为introws,这些变量又用于初始化columns类的实例。之后,我要计算类Airplane中这些变量的乘积。因此,我给出了值Flightrows = 2,并将columns = 3打印到0上。我提供的每个不同值都会不断返回console。您的帮助将不胜感激! 这是我的代码:

主类:

0

飞行舱:

  public class Main {
       public static void main(String[] args) {
           int counter=1;
           if (counter==1) {
               Scanner scanner = new Scanner(System.in);
               int rows, columns;
               Airplane airplane = new Airplane();
               rows = scanner.nextInt();
               airplane.setRows(rows);
               columns = scanner.nextInt();
               airplane.setColumns(columns);
               System.out.println(airplane.getColumns()*airplane.getRows());
               counter++;
           }
           if (counter==2){
                   Flight flight = new Flight();
                   int seats=0;
                   seats=flight.getNumberOfSeats();
                   System.out.println(seats);
            }
    }
}

飞机舱:

public class Flight {
    private int numberOfSeats;
    //getters and setters
}

2 个答案:

答案 0 :(得分:1)

在第二个if语句中,您创建了Flight的新实例,并且没有更改其任何字段值,因此,当您在此处读取座位数时,它的初始值仍为0( int的默认值)。 下面的代码应该可以满足您的要求。

public class Main {
   public static void main(String[] args) {
       int counter=1;
       Airplane airplane;
       if (counter==1) {
           Scanner scanner = new Scanner(System.in);
           int rows, columns;
           airplane = new Airplane();
           rows = scanner.nextInt();
           airplane.setRows(rows);
           columns = scanner.nextInt();
           airplane.setColumns(columns);
           System.out.println(airplane.getColumns()*airplane.getRows());
           counter++;
       }
       if (counter==2) {
           Flight flight = new Flight();
           flight.setNumberOfSeats(airplane.getColumns()*airplane.getRows());
           System.out.println(flight.getNumberOfSeats());
       }
   }
}

答案 1 :(得分:0)

我认为这是polymorphism and composition中的练习。这个想法很可能是Flight有一个Airplane HAS-A relation。您的Flight类将如下所示:

class Flight {
  private Airplane airplane;
  private int numberOfSeats;

  public Flight(Airplane airplane) {
    this.airplane = airplane;
    this.numberOfSeats = (airplane.getColumns() * airplane.getRows());
  }

  public void getNumberOfSeats() {
     return this.numberOfSeats;
  }


  public void setNumberOfSeats(int numberOfSeats) {
    this.numberOfSeats = numberOfSeats;
  }
}

现在在您的主要代码中,您只需要将Airplane的权限传递给Flight

Flight flight = new Flight(airPlane);

由于您已经在if范围之外定义了平面,如果将其更改为Airplane airplane = null;