Dem
Dem

Reputation: 61

CompareTo Function Issue

Help I cant figure out the compareTo Function. This is what I have to do: Write a compareTo function that can be used to place the products in order according to their part numbers. That is, a part number that is later in alphabetical order is greater than a part number that is earlier in alphabetical order. This is my code:

public class ProductType implements Comparable<ProductType> {
    private String partnum;
    private double price;
    private int stock;

    public ProductType(String partnum, double price, int stock) {
        this.partnum = partnum;
        this.price = price;
        this.stock = stock;
    }

    public ProductType() {
        partnum = "";
        price = 0;
        stock = 0;
    }

    public void setNum(String partnum) {
        this.partnum = partnum;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public void setStock(int stock) {
        this.stock = stock;
    }

    public String getNum() {
        return partnum;
    }

    public double getPrice() {
        return price;
    }

    public int getStock() {
        return stock;
    }

    public int compareTo(ProductType otherType) throws NullPointerExeption {
        if (otherType == null)
            throw new NullPointerException();
        return (this.getNum().compareTo.otherType.getNum());
    }

    public String toString() {
        String result = "" + this.getNum();
        return result;
    }
}

Upvotes: 0

Views: 107

Answers (1)

Prashant
Prashant

Reputation: 2614

change your return statement

 return (this.getNum().compareTo.otherType.getNum());

to

 return (this.getNum().compareTo(otherType.getNum()));

because compareTo() is method.

before calling compareTo() method check whether

null != this.getNum()

otherwise you will get NPE.

Upvotes: 4

Related Questions