Home > OS >  How to stop Java code from repeating last value of object array?
How to stop Java code from repeating last value of object array?

Time:03-01

I'm working on a project with a friend; we're trying to create an airplane project using a Passenger class for passengers, Airplane class to add in passengers and create the airplane, and a driver class. We've run into an issue where when we add in all the passengers to the airplane and print all details of the airplane, printed values are capturing only the last passenger's information. We're trying to get this for every passenger. Here is the code:

Passenger

public class Passenger {

    private String name;
    private int  birthYear;
    private double weight;
    private char gender;
    private int numCarryOn;

    //Default constructor
    public Passenger(){
        name = "";
        birthYear = 1900;
        weight = 0.0;
        gender = 'u';
        numCarryOn = 0;
    }

    //Alt default constructor
    public Passenger(String newName, int newBirthYear, double newWeight, char newGend, int newNumCarryOn){

        this.setName(newName);
        this.setBirthYear(newBirthYear);
        this.setWeight(newWeight);
        this.setGender(newGend);
        this.setNumCarryOn(newNumCarryOn);
    }

    //Calculate age
    public int calculateAge(int currentYear){

        int age = 0;

        if (currentYear < birthYear){
            return -1;
        }
        else {
            age = currentYear - birthYear;
        }

        return age;
    }

    //Gain weight
    public void gainWeight(){
        weight  = 1;
    }

    //Gain weight based on input
    public void gainWeight(double pounds){

        if (weight > 0){
            weight = weight   pounds;
        }

    }

    //Get birthYear
    public int getBirthYear(){
        return birthYear;
    }

    //Get gender
    public char getGender(){
        return gender;
    }

    //Get name
    public String getName(){
        return name;
    }

    //Get weight
    public double getWeight(){
        return weight;
    }

    //Get numCarryOn
    public int getNumCarryOn(){
        return numCarryOn;
    }

    //isFemale
    public boolean isFemale(){

        if (gender == 'f'){
            return true;
        }
        else {
            return false;
        }
    }

    //isMale
    public boolean isMale(){
        if (gender == 'm'){
            return true;
        }
        else {
            return false;

        }
    }

    //loseWeight
    public void loseWeight(){

        if (weight > 0){
            weight -= 1;
        }

    }

    //lose weight by value
    public void loseWeight(double weight2lose){

        if (weight - weight2lose >= 0){
            weight -= weight2lose;
        }

    }

    //print
    public void printDetails(){

        System.out.printf("Name:  s | Year of Birth: M | Weight: .2f | Gender: %c | NumCarryOn: -\n", name, birthYear, weight, gender, numCarryOn);

    }

    //setGender
    public void setGender(char newGender){

        if (newGender == 'f' || newGender == 'm') {
            this.gender = newGender;
        } else {
            this.gender = 'u';
        }
    }

    //setName
    public void setName(String newName){
        name = newName;
    }

    //setBirthYear
    public void setBirthYear(int newBY){
        birthYear = newBY;
    }

    //setWeight
    public void setWeight(double newWeight){

        if (newWeight < 0){
            weight = -1;

        }
        else {
            weight = newWeight;
        }

    }

    //setNumCarryOn
    public void setNumCarryOn(int newNumCarryOn){

        if (newNumCarryOn < 0){
            numCarryOn = 0;

        }
        else if (newNumCarryOn > 2){
            numCarryOn = 2;
        }
        else {
            numCarryOn = newNumCarryOn;
        }
    }
}

Airplane


public class Airplane {

    private Passenger[] passengers;
    private String airplaneName;
    private int numPassengers;
    public int count = 0;

    //default constructor
    public Airplane(){

        airplaneName = "";
        passengers = new Passenger[100];
        numPassengers = 0;
    }

    //default constructor with String input
    public Airplane(String otherairplaneName){

        airplaneName = otherairplaneName;
        passengers = new Passenger[100];
        numPassengers = 0;

    }

    //default constructor with int input
    public Airplane(int otherArraySize){

        airplaneName = "";

        if (otherArraySize < 0){
            otherArraySize = 0;
        }
        passengers = new Passenger[otherArraySize];


        numPassengers = 0;

    }

    //default constructor with String and int input
    public Airplane(String otherAirplaneName, int otherArraySize){

        airplaneName = otherAirplaneName;

        if (otherArraySize < 0){
            otherArraySize = 0;
        }

        passengers = new Passenger[otherArraySize];


        numPassengers = 0;

    }

    //add a passenger
    public void addPassenger(Passenger a){

        for (int i = 0; i < passengers.length; i  ){


           passengers[i] = a;



        }
    }


    //resize array for new passengers
    private void resizePassengerArray(){

        passengers = new Passenger[passengers.length * 2];

    }

    //get a passenger
    public Passenger getPassenger(int passengerIndex){

        return passengers[passengerIndex];
    }

    //getNumPassengers
    public int getNumPassengers() {

       return count;
    }

    //getFirstPassenger
    public Passenger getFirstPassenger(){

        return passengers[0];
    }

    //getLastPassenger
    public Passenger getLastPassenger(){

        return passengers[passengers.length - 1];
    }

    //getPassengers**
    public Passenger[] getPassengers(){

        return passengers;
    }

    //setAirplaneName
    public void setAirplaneName(String newAirplaneName){

        airplaneName = newAirplaneName;
    }

    //printAllDetails
    public void printAllDetails(){

        System.out.printf("AirplaneName:  s | Number of Passengers: M | Airplane Size: M\n", airplaneName, count, passengers.length);

        for (int i = 0; i < count; i  ){
            System.out.printf("Name:  s | Year of Birth: M | Weight: .2f | Gender: %c\n", passengers[i].getName(), passengers[i].getBirthYear(), passengers[i].getWeight(), passengers[i].getGender());

        }
    }

    //removePassenger
    public Passenger removePassenger(int passengerIndex){

        if (passengerIndex != passengers.length - 1){

            for (int i = passengerIndex; i < passengers.length - 1; i  ){

                passengers[i] = passengers[i 1];

            }
        }

        return passengers[passengerIndex];
    }

    //remove all passengers
    public void removeAllPassengers(){

       passengers = new Passenger[100];
    }

    //total weight passengers
    public double getTotalWeightOfAllPassengers(){

        double weight = 0.0;

        for (int i = 0; i < passengers.length; i  ){
            weight  = passengers[i].getWeight();
        }

        return weight;
    }

    //avg weight passengers
    public double getAverageWeightOfAllPassengers(){

        double avg = this.getTotalWeightOfAllPassengers() / numPassengers;

        return avg;
    }

    //num elements above weight
    public int getNumberOfPassengersAboveWeight(double weight){

        int sum = 0;

        for (int i = 0; i < passengers.length; i  ){

            if (passengers[i].getWeight() > weight){
                sum  = 1;
            }

        }

        return sum;
    }

    //num elements below weight
    public int getNumberOfPassengersBelowWeight(double weight){

        int sum = 0;

        for (int i = 0; i < passengers.length; i  ){

            if (passengers[i].getWeight() < weight){
                sum  = 1;
            }

        }

        return sum;
    }

    //increase weight of passengers
    public void increaseWeightOfAllPassengers(){

        for (int i = 0; i < passengers.length; i  ){
            passengers[i].gainWeight();
        }

    }

    //increase weight of passengers with weight input
    public void increaseWeightOfAllPassengers(double increaseAmount){

        for (int i = 0; i < passengers.length; i  ){
            passengers[i].gainWeight(increaseAmount);
        }

    }



}

Driver

public class RunAirplane {
    public static void main(String[] args) {
        Airplane a1 = new Airplane("Flight 1", 100);
        Passenger p1 = new Passenger("Albert", 1879, 198.5, 'm', 2);
        Passenger p2 = new Passenger("Grace", 1906, 105, 'f', 1);
        Passenger p3 = new Passenger("Tim", 1955, 216.3, 'm', 2);
        Passenger p4 = new Passenger("Steve", 1955, 160, 'm', 2);
        Passenger p5 = new Passenger("Sergey", 1973, 165.35, 'm', 1);

        a1.addPassenger(p1);
        a1.count  = 1;
        a1.addPassenger(p2);
        a1.count  = 1;
        a1.addPassenger(p3);
        a1.count  = 1;
        a1.addPassenger(p4);
        a1.count  = 1;
        a1.addPassenger(p5);
        a1.count  = 1;
        a1.printAllDetails();

        //How it should work starting with name
        System.out.println(p1.getName());
        System.out.println(p2.getName());

    }
}

Here's a screenshot of the incorrect code: https://imgur.com/TGc0FQa

CodePudding user response:

The addPassenger() method is overwriting every element in the array:

public void addPassenger(Passenger a){
    for (int i = 0; i < passengers.length; i  ){
       passengers[i] = a;
    }
}

It should just set the one at the next available index, which happens to be count:

public void addPassenger(Passenger a){
    passengers[count  ] = a;
}

This also gives you better encapsulation, as you don't have to expose and increment count externally.

CodePudding user response:

this

    public void addPassenger(Passenger a){

        for (int i = 0; i < passengers.length; i  ){


           passengers[i] = a;



        }
    }

Produce every time a Passenger Array full with the same Passenger. Perhaps this might solve the problem.


public void addPassenger(Passenger a){

        for (int i = 0; i < passengers.length; i  ){

          if((passengers[i-1] !=null)&&((passengers[i] ==null))
          { passengers[i] = a; }




        }
    }

A better implementation could be with ArrayList

Airplane


public class Airplane {

    private ArrayList<Passenger> passengers;
    private String airplaneName;
    private int numPassengers;
    public int count = 0;

    //default constructor
    public Airplane(){

        airplaneName = "";
        passengers = new ArrayList();
        numPassengers = 0;
    }

    //default constructor with String input
    public Airplane(String otherairplaneName){

        airplaneName = otherairplaneName;
        passengers = new ArrayList();
        numPassengers = 0;

    }

    

    //default constructor with String and int input
    public Airplane(String otherAirplaneName){

        airplaneName = otherAirplaneName;


        passengers = new ArrayList();


        numPassengers = 0;

    }

    //add a passenger
    public void addPassenger(Passenger a){
        
        passengers.add(a);
      
    }


    //get a passenger
    public Passenger getPassenger(int passengerIndex){

        return passengers[passengerIndex];
    }

    //getNumPassengers
    public int getNumPassengers() {

       return count;
    }

    //getFirstPassenger
    public Passenger getFirstPassenger(){

        return passengers.get(0);
    }

    //getLastPassenger
    public Passenger getLastPassenger(){

        return passengers.get(passengers.size() - 1);
    }

    //getPassengers**
    public ArrayList<Passenger> getPassengers(){

        return passengers;
    }

    //setAirplaneName
    public void setAirplaneName(String newAirplaneName){

        airplaneName = newAirplaneName;
    }

    //printAllDetails
    public void printAllDetails(){

        System.out.printf("AirplaneName:  s | Number of Passengers: M | Airplane Size: M\n", airplaneName, count, passengers.size());

        for (int i = 0; i < count; i  ){
            System.out.printf("Name:  s | Year of Birth: M | Weight: .2f | Gender: %c\n", passengers.get(i).getName(), passengers[i].get(i).getBirthYear(), passengers[i].get(i).getWeight(), passengers[i].get(i).getGender());

        }
    }

    //removePassenger
    public Passenger removePassenger(int passengerIndex){

            passengers.remove(passengerIndex);

        return passengers.get(passengerIndex);
    }

    //remove all passengers
    public void removeAllPassengers(){

       passengers = new ArrayList();
    }

    //total weight passengers
    public double getTotalWeightOfAllPassengers(){

        double weight = 0.0;

        for (int i = 0; i < passengers.size(); i  ){
            weight  = passengers.get(i).getWeight();
        }

        return weight;
    }

    //avg weight passengers
    public double getAverageWeightOfAllPassengers(){

        double avg = this.getTotalWeightOfAllPassengers() / numPassengers;

        return avg;
    }

    //num elements above weight
    public int getNumberOfPassengersAboveWeight(double weight){

        int sum = 0;

        for (int i = 0; i < passengers.size(); i  ){

            if (passengers.get(i).getWeight() > weight){
                sum  = 1;
            }

        }

        return sum;
    }

    //num elements below weight
    public int getNumberOfPassengersBelowWeight(double weight){

        int sum = 0;

        for (int i = 0; i < passengers.size(); i  ){

            if (passengers.get(i).getWeight() < weight){
                sum  = 1;
            }

        }

        return sum;
    }

    //increase weight of passengers
    public void increaseWeightOfAllPassengers(){

        for (int i = 0; i < passengers.size(); i  ){
            passengers.get(i).gainWeight();
        }

    }

    //increase weight of passengers with weight input
    public void increaseWeightOfAllPassengers(double increaseAmount){

        for (int i = 0; i < passengers.size(); i  ){
            passengers.get(i).gainWeight(increaseAmount);
        }

    }



}

CodePudding user response:

The issue is in the method addPassenger. You are replacing always the first element.

You can fix in this way:

public void addPassenger(Passenger a){
    passengers[count] = a;
    count  
}

For better implementation, you can remove count and use numPassengers.

Therefore the method becomes:

public void addPassenger(Passenger a){
    passengers[numPassengers] = a;
    numPassengers  
}

and the main class:

public class RunAirplane {
    public static void main(String[] args) {
        Airplane a1 = new Airplane("Flight 1", 100);
        Passenger p1 = new Passenger("Albert", 1879, 198.5, 'm', 2);
        Passenger p2 = new Passenger("Grace", 1906, 105, 'f', 1);
        Passenger p3 = new Passenger("Tim", 1955, 216.3, 'm', 2);
        Passenger p4 = new Passenger("Steve", 1955, 160, 'm', 2);
        Passenger p5 = new Passenger("Sergey", 1973, 165.35, 'm', 1);

        a1.addPassenger(p1);
        a1.addPassenger(p2);
        a1.addPassenger(p3);
        a1.addPassenger(p4);
        a1.addPassenger(p5);
        a1.printAllDetails();

        //How it should work starting with name
        System.out.println(p1.getName());
        System.out.println(p2.getName());

    }
}

For the best implementation, you can use List instead of an array for the field passengers:

private List<Passenger> passengers;
public Airplane(){
    airplaneName = "";
    passengers = new ArrayList<>();
}
public void addPassenger(Passenger a){
    passengers.add(a);
}

You can remove the numPassengers and use size:

public int getNumPassengers() {
   return passengers.size();
}
  • Related