Home > Blockchain >  Java - returning object arbitrarily that repeats more then one
Java - returning object arbitrarily that repeats more then one

Time:03-14

I have a class that relies on three classes I have created before. I have a method in the 4th class, in which I was requested to get the newest Car object. If there is more, from one such, one of them will be returned arbitrarily. The method called getNewest()

Posting the current class and the one before it to reference for you to make the connection:

Previous 3rd class -> Car

public class Car {

private  Owner _owner; //an object from 1st class
private String _manufacturer;
private boolean _airbag;
private boolean _leasingOrRental;
private int _km, _seats, _year;
private int _price;
private int _LevyPrice;
private Bid _highestBid;//an object from 2st class

public Car(Owner ow, String mfr, boolean isAirbag, boolean leasOrRent, int kilNum, int seatNum, int date, int price, int levy, Bid high) // Constructor
{
    _owner = new Owner(ow);
    _manufacturer = mfr;
    _airbag = isAirbag;
    _leasingOrRental = leasOrRent;
    _km = kilNum;
    _seats = seatNum;
    _year = date;
    _price = price;
    _LevyPrice = levy;
    _highestBid = new Bid(high);
}

public Car(Car other) //copy constrcutor 
{
    _owner = new Owner(other._owner);
    _manufacturer = other._manufacturer;
    _airbag = other._airbag;
    _leasingOrRental = other._leasingOrRental;;
    _km = other._km;
    _seats = other._seats;;
    _year = other._year;
    _price = other._price;
    _LevyPrice = other._LevyPrice;
    _highestBid = new Bid(other._highestBid); 
}

public Owner getOwner()
{
    return new Owner(_owner);
}

public String getManufacturer()
{
    return _manufacturer;
}

public boolean getAirbag()
{
    return _airbag;
}

public boolean getIsleasingOrRental()
{
    return _leasingOrRental;
}

public int getKm() {
    return _km;
}

public int getSeats() {
    return _seats;
}

public int getYear() {
    return _year;
}

public int getLevyPrice() {
    return _LevyPrice;
}

public Bid getHighestBid() {
    return new Bid(_highestBid);
}

public void makeBid(Bid bid)
{
    if (_highestBid.getBidPrice() < bid.getBidPrice())
        _highestBid.setBidPrice(bid.getBidPrice());
}

public boolean isAttractive()
{
    return _airbag == true && _leasingOrRental == true && (_km > 0 && _km < 20000 ) && _year >= 3;
}

public boolean fitForFamily(int kids)
{
    return _seats - 2 >= kids;
}

public boolean overUsedCar()
{
    final int KILOMERTES = 12000;

    return _km > KILOMERTES*(2022 - _year);
}

public String toString()
{
    return "Manufacturer: " _manufacturer "\n"
             "Year: " _year "\n"
             "Owner: " _owner.toString() "\n"
             "Highest bid: " _highestBid.getBidPrice();
}

}

4th and current class CarSales with

public class CarSales {

private Car[] _cars;
int _noOfCars;

public CarSales(int size)
{
    _cars = new Car[size];
    _noOfCars = 0;
}

public boolean addCar(Car car)
{
    int size = _cars.length 1;
    //_cars = new Car[_noOfCars];
    if(_cars.length < _noOfCars)
    {
        _cars[size] = new Car(car);
        return true;
    }
    else
    {
        return false;
    }
}

public Car getNewest()
{
    Car newest = _cars[0];
    Car [] _new = new Car[_noOfCars];
    int size = 0;
    for (int i = 1; i < _cars.length; i  )
        if(newest.getYear() < _cars[i].getYear())
            newest = _cars[i];

    for (int i = 0; i < _cars.length; i  )
        if (newest.getYear() == _cars[i].getYear())
            size  ;

    for (int i = 0; i < _cars.length; i  )
        if (newest.getYear() == _cars[i].getYear())
            _new[i] = new Car(_cars[i]);

    return _new[0];
}
}

In my method I created, I'm returning the first object, but I can return it after the first loop if I'm doing this that way from the start. But I want to make the option to return the object arbitrarily if I have more than one object. Also, if there is a way to make it more efficient, I would appreciate your example.

Cannot use ArrayList lang like add or copy or indexOf must be done logically.

Thanks in advance for all helpers and feedback.

CodePudding user response:

In the constructor of class CarSales, you initialize _cars. Here is the relevant line from the code in your question.

_cars = new Car[size];

This creates an array of size elements but every element is null. Hence the purpose of _noOfCars is to tell you how many non-null elements are in the array _cars. Therefore, in all the for loops in method getNewest (in class CarSales) you need to iterate through all the non-null elements of array _cars rather than through all the elements. Hence each for loop should be:

for (int i = 0; i < _noOfCars; i  )

Consequently, method addCar (also in class CarSales) needs to update _noOfCars. Here is the corrected method.

public boolean addCar(Car car) {
    if (_noOfCars < _cars.length) {
        _cars[_noOfCars  ] = car;
        return true;
    }
    else {
        return false;
    }
}

I assume that in method getNewest you want to return a random element from the array containing all the newest cars. In the below code, I use class ThreadLocalRandom to generate a random index for the array.

public Car getNewest() {
    Car newest = _cars[0];
    int size = 0;
    for (int i = 1; i < _noOfCars; i  )
        if (newest.getYear() < _cars[i].getYear())
            newest = _cars[i];

    for (int i = 0; i < _noOfCars; i  )
        if (newest.getYear() == _cars[i].getYear())
            size  ;

    Car[] _new = new Car[size];
    int ndx = 0;
    for (int i = 0; i < _noOfCars; i  )
        if (newest.getYear() == _cars[i].getYear())
            _new[ndx  ] = new Car(_cars[i]);

    return _new[ThreadLocalRandom.current().nextInt(0, _new.length)];
}

Here is a complete example. Since you didn't post the code for classes Owner and Bid, I made up minimal definitions for them and I also added a main method to class Car so as to get a complete program that can be compiled and run.

import java.util.concurrent.ThreadLocalRandom;

public class Car {
    private Owner _owner; // an object from 1st class
    private String _manufacturer;
    private boolean _airbag;
    private boolean _leasingOrRental;
    private int _km, _seats, _year;
    private int _price;
    private int _LevyPrice;
    private Bid _highestBid;// an object from 2st class

    // Constructor
    public Car(Owner ow,
               String mfr,
               boolean isAirbag,
               boolean leasOrRent,
               int kilNum,
               int seatNum,
               int date,
               int price,
               int levy,
               Bid high) {
        _owner = ow; // new Owner(ow);
        _manufacturer = mfr;
        _airbag = isAirbag;
        _leasingOrRental = leasOrRent;
        _km = kilNum;
        _seats = seatNum;
        _year = date;
        _price = price;
        _LevyPrice = levy;
        _highestBid = high; // new Bid(high);
    }

    // copy constrcutor
    public Car(Car other) {
        _owner = other._owner; // new Owner(other._owner);
        _manufacturer = other._manufacturer;
        _airbag = other._airbag;
        _leasingOrRental = other._leasingOrRental;
        _km = other._km;
        _seats = other._seats;
        _year = other._year;
        _price = other._price;
        _LevyPrice = other._LevyPrice;
        _highestBid = other._highestBid; // new Bid(other._highestBid);
    }

    public Owner getOwner() {
        return _owner; // new Owner(_owner);
    }

    public String getManufacturer() {
        return _manufacturer;
    }

    public boolean getAirbag() {
        return _airbag;
    }

    public boolean getIsleasingOrRental() {
        return _leasingOrRental;
    }

    public int getKm() {
        return _km;
    }

    public int getSeats() {
        return _seats;
    }

    public int getYear() {
        return _year;
    }

    public int getLevyPrice() {
        return _LevyPrice;
    }

    public Bid getHighestBid() {
        return _highestBid; // new Bid(_highestBid);
    }

    public void makeBid(Bid bid) {
        if (_highestBid.getBidPrice() < bid.getBidPrice())
            _highestBid.setBidPrice(bid.getBidPrice());
    }

    public boolean isAttractive() {
        return _airbag == true && _leasingOrRental == true && (_km > 0 && _km < 20000)
                && _year >= 3;
    }

    public boolean fitForFamily(int kids) {
        return _seats - 2 >= kids;
    }

    public boolean overUsedCar() {
        final int KILOMERTES = 12000;

        return _km > KILOMERTES * (2022 - _year);
    }

    public String toString() {
        return "Manufacturer: "   _manufacturer   "\n"   "Year: "   _year   "\n"   "Owner: "
                  _owner.toString()   "\n"   "Highest bid: "   _highestBid.getBidPrice();
    }

    public static void main(String[] args) {
        CarSales carSales = new CarSales(5);
        Car carOne = new Car(new Owner("George"), "mfr", true, true, 0, 5, 2020, 1, 1, new Bid(2));
        carSales.addCar(carOne);
        Car carTwo = new Car(new Owner("May"), "mfr", true, true, 0, 5, 2020, 2, 2, new Bid(4));
        carSales.addCar(carTwo);
        System.out.println(carSales.getNewest());
    }
}

class CarSales {
    private Car[] _cars;
    private int _noOfCars;

    public CarSales(int size) {
        _cars = new Car[size];
        _noOfCars = 0;
    }

    public boolean addCar(Car car) {
        if (_noOfCars < _cars.length) {
            _cars[_noOfCars  ] = car;
            return true;
        }
        else {
            return false;
        }
    }

    public Car getNewest() {
        Car newest = _cars[0];
        int size = 0;
        for (int i = 1; i < _noOfCars; i  )
            if (newest.getYear() < _cars[i].getYear())
                newest = _cars[i];

        for (int i = 0; i < _noOfCars; i  )
            if (newest.getYear() == _cars[i].getYear())
                size  ;

        Car[] _new = new Car[size];
        int ndx = 0;
        for (int i = 0; i < _noOfCars; i  )
            if (newest.getYear() == _cars[i].getYear())
                _new[ndx  ] = new Car(_cars[i]);

        return _new[ThreadLocalRandom.current().nextInt(0, _new.length)];
    }
}

class Bid {
    private double bidPrice;

    public Bid(double price) {
        bidPrice = price;
    }

    public double getBidPrice() {
        return bidPrice;
    }

    public void setBidPrice(double bidPrice) {
        this.bidPrice = bidPrice;
    }
}

class Owner {
    private String name;

    public Owner(String name) {
        this.name = name;
    }

    public String toString() {
        return name;
    }
}
  • Related