Firstly I have 3 classes with getters and setters. In the Main class I scan two variables of type int
called rows
and columns
, which are in turn used to initialise an instance of the Airplane
class. After this I want to calculate the product of these variables in class Flight
. So I gave the values rows = 2
and columns = 3
and it printed 0
to the console
. Every different value I give keeps returning 0
as a result. Your help will be appreciated! Here is my code:
Main class:
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);
}
}
}
Flight class:
public class Flight {
private int numberOfSeats;
//getters and setters
}
Airplane class:
public class Airplane {
private int rows;
private int columns;
//getters and setters
}
In the second if statement you created a new instance of Flight
and you haven't changed any of its field values, so consequently when you are reading the number of seats here it still has the initial value 0 (the default value for an int). The code below should do what you want.
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());
}
}
}
I think this is an exercise in polymorphism and composition . It is likely that the idea is that a Flight
has an Airplane
HAS-A relation . Your Flight
class will than look like this:
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;
}
}
In your main code you now only have to pass the reverence of the Airplane
to the Flight
.
Flight flight = new Flight(airPlane);
Since you already defined the plane outside the if
scope this can be done, if you change it to Airplane airplane = null;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.