1.11M Members

Arraylist using methods from other class help!!

 
0
 

Hello guys well I have been working in this arraylist that is now driving me crazy!
Bascially I wrote a CAR class which has some methods in it, however now I created an arraylist so it could store cars from the other class and at the same time have access to some of the methods of that class such as rentTheCar or returnCar. I am having trouble with three things.
First showCar is just now working properly it shows me all the cars although I put the carNumber when I invoke the method, moreover I want the method to print the description of that particular car.

The rentTheCar method is renting the car, well Basically renting all the cars at the same time instead of renting the car with carNumber specified when invoking the method.

The return car method does exactly the exact same as the rentTheCar method but in this case it returns them all insetad of just returning the car specified when invoking the method.

Here I leave both classes:

public class Car
{
    // This represents the car's features entered by the user.
    private String description;
    // This represents the name of the user or the person that will rent the car.
    private String name;
    // This represents the days that the car will be rented for.
    private int days;
    // This represents the down payment made bny the user to rent the car. 
    private int deposit;
    // This represents the daily rate of rental for the car.
    private int rate;
    // This represents the start date of the rental. 
    private String dateOfHire;
    // This represents the date that the car will be returned. 
    private String dateOfReturn;
    // This represents the total amount of money that will be paid until the end of the rental.
    private int totalRent;
    // This represents the status of the car, that can be rented or not rented.
    private boolean onLoan;
    
    /**
     * Stablish a car with first features such as description and rate. 
     */
    public Car(String carDescription, int dailyRate, int downPayment)
    {
        description = carDescription;
        rate = dailyRate;
        days = 0;
        name = "";
        dateOfHire = "";
        dateOfReturn = "";
        deposit = downPayment;
        totalRent = 0;
        onLoan = false;
        
        
    }

    /**
     * This is a method that returns the car's description
     */
    public String getDescription()
    {
        return description;
    }
    
    /**
     * This is a method that displays on screen the rental review.
     * The rental review consists of the description, customer's name, start date, 
     * return date, period of time, down payment, amount due, daily rate.
     */
    public void displayDescription()
    {
       System.out.println(" Rental Review ");
       System.out.println("The car will be a " + description);
       System.out.println("The daily rate is £" + rate);
       System.out.println("It will be rented to " + name);
       System.out.println("From "+ dateOfHire);
       System.out.println("To " + dateOfReturn);
       System.out.println("Hired for " + days + " days");
       System.out.println("The Down Payment is £ " + deposit);
       System.out.println("The amount to be paid at the end of the rental is £ " + (rate*days));
       System.out.println("The total payment is £ " + (deposit + (rate*days)));
    }
    
    /**
     * This is a method that returns the daily rate of the specific car.
     */
    public int getDailyRate()
    {
        return rate;
    }
    
    /**
     * This is a method that sets a new daily rate for the car if required.
     */
    public int newDailyRate(int newRate)
    {
        rate = newRate;
        return rate;
    }
    
    /**
     * This represents the simple action of renting a car and retrieving some information
     * such us the customer's name, start date, return date, total days of rental and the downpayment.  
     */
    public void rentTheCar(String CustomerName, String hireDate, String returnDate, int daysOfHire)
    {
        if (onLoan == true) { 
        System.out.println("Error!! This car is already rented. It wil be available the " + dateOfReturn);
       }
       else {
           
           name = CustomerName;
           dateOfHire = hireDate;
           dateOfReturn = returnDate;
           days = daysOfHire;
           onLoan = true;
           totalRent = totalRent + ((rate * days) + deposit);
           
        
        }
    
    }


/**
     * This is a method that returns the customers full name.
     */
    public String getCustomerName()
    {
        return name;
    }

    
    /**
     * This is a method that returns the start date of the rental.
     */
    public String getHireDate()
    {
        return dateOfHire;
    }
    
     
    /**
     * This is a method that returns the car's date of return.
     */
    public String getReturnDate()
    {
        return dateOfReturn;
    }
    
    /**
     * This is a method that returns the total days that the car will be rented for.
     */
    public int getDaysOfHire()
    {
        return days;
    }
    
    /**
     * This is a method that returns the down payment that the customer will need to 
     * pay, to rent the car.
     */
    public int getDownPayment()
    {
        return deposit;
    }
    
    /**
     * This is a method that sets a new down payment if required.
     */
    public int newDownPayment(int newDeposit)
    {
        deposit = newDeposit;
        return deposit;
    }
    
    /**
     * This represents the simple action of returning the car and reseting some information and values
     * such us the customer's name, start date, return date, total days of rental and the downpayment.
     */
    public void returnTheCar()
    {
        if (onLoan == true) {
           name = "";
           dateOfHire = "";
           dateOfReturn = "";
           days = 0;
           totalRent = 0;
           onLoan = false;
        }
        else {
           System.out.println("Error!! This car is not rented! "); 
    }
   }
  }

and now the Rental arraylist

import java.util.ArrayList;


public class rentalCompany
{
   
    private ArrayList<Car>cars;
    private int i;
    
  

    /**
     * Constructor for objects of class RentalCompany
     */
    public rentalCompany ()
    {
        cars = new ArrayList<Car>();
        
    }
    
    /**
     * Constructor for objects of class RentalCompany
     */
    public void createCar(String carDescription, int downPayment, int dailyRate){
       cars.add( new Car (carDescription, downPayment, dailyRate));
       
    }
        


    public void removeCar (int carNumber)
    {
        if (cars.size() < 0){
            System.out.println ("Error!! It is impossible to remove a car from an empty list");
        }
        if (cars.size() == cars.size()) {
            cars.remove(carNumber);
        }
    }
    
   
     */
    public void returnCar (int carNumber)
    {
        cars.get(carNumber);
        if (cars.size() < 0) {
           System.out.println("Error!! It is impossible to return a car from an empty list");
           }
           else if (carNumber > cars.size()) {
            System.out.println("Error!! Not a valis car!!");
            }
        else {
            for (Car car : cars) {
            
            car.returnTheCar();
            System.out.println ("The car has been returned correctly");
           }
            }
        
          
        }
    
        

    
       */
    public void rentTheCar (int carNumber, String CustomerName, String hireDate, String returnDate, int daysOfHire)
    {
         
        if (cars.size() < 0) {
           System.out.println("Empty list!! Add cars first!!");
           }
           else if (carNumber > cars.size()) {
               System.out.println("This car does not exist!!");
            }
        else {
            cars.get (carNumber);
            for (Car car : cars) {
            car.rentTheCar(CustomerName, hireDate, returnDate, daysOfHire);
          
          }
        } 

        }
    

    /**
     * Constructor for objects of class RentalCompany
     */
    public int numberOfCars()
    {
        return cars.size();
    }
    
    /**
     * Constructor for objects of class RentalCompany
     */
    public void showAllCars ()
    {
        for ( Car car:cars) { 
        if (cars.size()>0) {

            int i = 0;
            System.out.println(car.getDescription());
            i++;
            
        }
        else if ( cars.size() < 0 ){
            System.out.println ("Add cars first");
        }
       }
    }
    

    
    /**
     * Constructor for objects of class RentalCompany
     */
    public void showCar (int carNumber)
    {
        
    }
   

     public Car searchCar(String description, String parameter2)
    {
        for (Car car : cars) {
            if (car.getDescription() == description) {
                return car; 
            }
            else {
                System.out.println("This car is not listed. Retry!!");
            }
        }
        return null;
    }
   
    public void clearScreen()
     {
      System.out.print('\u000C');
     }
   }

Thanks for all your help!!

 
0
 

In your rent and return methods, you're looping the whole list and acting on every car

for (Car car : cars) {...

You need to get() just the one car and operate only on that car object.

 
0
 

Thanks very much for your response. It did work !! But for example I create a car just 1 (that would be index 0 in the arraylist) in this case and just to try if it prints an error I put return car 1 it returns an error in BlueJ like this

java.lang.indexOutOfBoundsException:
index: 1, size:1 (in java.util.Arralist)

My code now is:

public void returnCar (int carNumber)
    {

        if (cars.size() < 0) {
           System.out.println("Error!! It is impossible to return a car from an empty list");
           }
        if (carNumber > cars.size()) {
            System.out.println("Error!! Not a valid car!!");
            }
        else {
            Car car = cars.get(carNumber);
            car.returnTheCar();
            System.out.println ("The car has been returned correctly");
        
            } 
        }

The rentTheCar now is:

public void rentTheCar (int carNumber, String CustomerName, String hireDate, String returnDate, int daysOfHire)
    {
         
        if (cars.size() < 0) {
           System.out.println("Empty list!! Add cars first!!");
           }
           else if (carNumber > cars.size()) {
               System.out.println("This car does not exist!!");
            }
        else {
            Car car = cars.get(carNumber);
            car.rentTheCar(CustomerName, hireDate, returnDate, daysOfHire);
          
          
        } 

        }
 
0
 

Don't forget that index==size() is also too large. Double check your verification code with that in mind.

 
0
 

In this case would it be possible to make it start the count from 1 and not from 0?

 
0
 

No, Java uses zero-based indexing almost exclusively. You can't change it to start at 1.

The fix I'm referring to is not difficult and is something you'll need to get used to in Java. In all places where you check if carNum is greater than size(), you simply need to amend the operator you're using. If the index equals size, that is also an invalid index.

 
0
 

Ok now I understand basically if the index is 10 the size is 11 because java counts from 0, so if i put as carNum 1 when the size() is 1 then thats not really a valid car number. Thanks very much for your help. I still have lots to learn! Could you maybe guide me throw the showAllCars method? thats the last thing to get fixed. Basically it has to show me all cars not onloan, well basically index + carDescription from all not onloan cars Thanks very much for all your help until now

 
0
 

If you want to print out the index along with the description, you can use the following basic idea:
1) for() loop over the list, from 0 to size-1.
2) inside the loop, get() each car and check if not onloan
3) if not onLoan, print the index (which is your loop variable) + getDescription()

If you prefer to use the for-each loop you started with, consider the following:
1) if (cars.size()>0) isn't really needed because for-each loops automatically only loop through elements that are in the list. If it's empty, the loop just doesn't do anything.
2) This seems counterproductive to counting: int i = 0;

 
0
 

I am struggling a little bit with "2) inside the loop, get() each car and check if not onloan" How do I check if they are onLoan or not? In the car class the boolean is basically a

private boolean onLoan;

I just do not get how to retrieve whether the boolean si true or false in the arraylist. The problem is that nothing can be added to the car class, because my idea was to maybe add a public boolean method that would return whether the car was onLoan or not

Public boolean isOnLoan {
              return onLoan;
            }

but in this case nothing can be added into the car class

Thank you!!

 
0
 

If the rental company must display the cars that are available, it must have some access to tell if the car is currently rented.
I'm not sure what you are expected to do there because I don't know all the parameters and expectations of your assignment.

Perhaps you can check one of the other properties that you do have public access to? The data for a few of them looks like it will be easy to tell if the car is rented.

 
0
 

there is three public methods in the car class that use the boolean onLoan, however there is no one method itself that returns the boolean , so I need to find a way to use the boolean to see whether the car is onLoan or not, It is important to say that I cannot add the public method to return the boolean in the car class.

car class methods that use the boolean onLoan

in this case when creating the car it automatically sets the onLoan to false.

public Car(String carDescription, int dailyRate, int downPayment)
    {
        description = carDescription;
        rate = dailyRate;
        days = 0;
        name = "";
        dateOfHire = "";
        dateOfReturn = "";
        deposit = downPayment;
        totalRent = 0;
        onLoan = false;

2)
when renting it it sets it to true

public void rentTheCar(String CustomerName, String hireDate, String returnDate, int daysOfHire)
    {
        if (onLoan == true) { 
        System.out.println("Error!! This car is already rented. It wil be available the " + dateOfReturn);
       }
       else {
           
           name = CustomerName;
           dateOfHire = hireDate;
           dateOfReturn = returnDate;
           days = daysOfHire;
           onLoan = true;
           totalRent = totalRent + ((rate * days) + deposit);
           
        
        }
    
    }

3) when returning it, it sets the values to "default"

public void returnTheCar()
    {
        if (onLoan == true) {
           name = "";
           dateOfHire = "";
           dateOfReturn = "";
           days = 0;
           totalRent = 0;
           onLoan = false;
        }
        else {
           System.out.println("Error!! This car is not rented! "); 
    }
   }
 
0
 

Maybe you can use !getHireDate().equals(""); because that value seems to be set during a hire, and cleared on a return?

 
0
 

Exactly that value is set when creating the car as false and when the car is rented it changes to true then when you return the car it changes to false again. So would that work? My problem is that I do not know how to access that information of the boolean since it is not a public method if you know what I mean. Thanks!!

 
0
 

The value i need to get would be the onLoan not the HireDate. The method showAllCars needs to show me all the cars that are currently not on loan in the arraylist.

 
0
 

Yes. I understood that.
If a car is on loan it will have a hireDate. If it is not on loan it's hireDate will be "". The hire date can be used to tell the same thing as the onLoan boolean.

 
0
 

Right!! now I see what you are trying to say! That is a really good idea! I will try it and let you know what is happening and if I got it to work Thank very much! and sorry for being silly ! Thanks!

 
0
 

i am working on the same project, how do you check onloan/hiredate status using for each loop...please i need help:)

 
0
 

Do not hijack old threads. If yo have a new question, start your own thread.

 
0
 

Happy

Don't forget to declare the generic type of your ArrayList using parameterization, so as to avoid deprecation warnings. So if you want to store an ArrayList of Strings, you would write ArrayList<String> as the type.

Also, no need to use an Iterator in this case when we can use a for loop or a foreach loop. It will be more memory efficient. So for example:
view source
print?
1 for(int i = 0; i < listName.size(); i++){
2 //access ArrayList using get(int index) method
3 }

You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: