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;
}
}
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.
Related
I have two classes: Position and Order. In Position class, fields like: name, price. In Order class field: quantity. My problem is how to display: name, price and quantity together in Order class. I thought about delete arraylist and make another one with position and quantity but I doubt it would help me.
package programming.com.pl;
public class Position {
private String name;
private double price = 0;
public Position(String name, double price){
this.name = name;
this.price = price;
}
public double getPrice() {
return price;
}
public String toString(){
String str = String.format("%4s,%4s", name,price);
return str;
}
}
public class Order {
private int quantity;
final private ArrayList<Position> positions = new ArrayList<Position>();
private int addedPosition;
public Order(int quantity) {
this.quantity = quantity;
}
private double calculateProduct() {
double sum = 0;
for (int i = 0; i < positions.size(); i++) {
sum = positions.get(i).getPrice();
}
return sum;
}
double sumOrder() {
double sum = 0;
for (Position x : positions) {
sum += calculateProduct();
}
return sum;
}
void addPosition(Position p) {
if (!positions.contains(p)) {
positions.add(p);
} else {
quantity++;
}
}
void deletePosition(int index) {
positions.remove(index);
}
public String toString() {
System.out.println("Order is: ");
for (Position p : positions) {
System.out.println(positions.toString());
}
return "Order sum is: " + sumOrder();
}
}
You already are overriding toString method in Position class so you just need to call that toString method on the position object when iterating the position objects from inside your Order class' toString() method.
And as #Federico points out in the comments you shouldn't System.out.println from toString methods. Just append to a string the details you require displaying and return that string.
You can achieve your desired result like so:
public class Position {
.
.
#Override
public String toString() {
return String.format("%4s,%4s\n", name, price);
}
}
public class Order {
.
.
#Override
public String toString() {
StringBuilder sb = new StringBuilder("Order details: \n");
sb.append("Quantity: ").append(quantity).append("\n");
for (Position p : positions) {
sb.append(p);
}
sb.append("Order sum is: ").append(sumOrder());
return sb.toString();
}
}
in my recent uni work ive been given a task which i believe is to reassign values that have been set by getters and setters. The exact question is
" Edit the product’s main information that shares among all class such as ID,
Description, etc"
My attempt at this question is as followed.
public void editProductInformation() { //Standard level task 2 method 3
this.ID = 456890;
this.description = "Eggs";
this.recommendedUnitPrice = 10;
this.Unit = 6;
this.weight = 750;
}
}
this is also the code for the rest of the class
public class Product {
Scanner input = new Scanner(System.in);
protected int ID;
protected String description;
protected double recommendedUnitPrice;
protected double actualPrice;
protected int Unit = 1;
protected double weight;
protected LocalDate expiaryDate;
protected LocalDate expireDate;
public Product(int ID, String description, double recommendedUnitPrice, int unit, double weight, LocalDate expiarayDate) {
this.ID = ID;
this.description = description;
this.recommendedUnitPrice = recommendedUnitPrice;
this.Unit = unit;
this.weight = weight;
this.expiaryDate = expiarayDate;
}
public int getID() {
return this.ID;
}
public void setID(int ID) {
this.ID = ID;
}
public String getDescription() {
return this.description;
}
public void setDescripption(String description) {
this.description = description;
}
public double getRecommendedUnitPrice() {
return this.recommendedUnitPrice;
}
public void setRecommendedUnitPrice(double recommendedUnitPrice) {
this.recommendedUnitPrice = recommendedUnitPrice;
}
public int getUnit() {
return this.Unit;
}
public void setUnit(int unit) {
this.Unit = unit;
}
public double getWeight() {
return this.weight;
}
public void setWeight(double Weight) {
this.weight = Weight;
}
public LocalDate getExpiaryDate() {
return expiaryDate;
}
public void setExpiaryDate(LocalDate expiaryDate) {
this.expiaryDate = expiaryDate;
}
public void setPrice() {
System.out.println("Enter the price: ");
this.actualPrice = input.nextDouble();
}
public void setExpireDate() {
System.out.println("Enter the given date: ");
int day = input.nextInt();
int month = input.nextInt();
int year = input.nextInt();
LocalDate date = LocalDate.of(day, month, year);
this.expireDate = date;
}
public void comparePrice() { // Standard level task 2 method 1
if (recommendedUnitPrice == actualPrice) {
System.out.println("Price is equal");
} else if (recommendedUnitPrice < actualPrice) {
System.out.println("Price is less");
} else if (recommendedUnitPrice > actualPrice) {
System.out.println("Price is more");
}
}
public void verifyExpireProduct() { //Standard level task 2 method 2
if(expireDate == expiaryDate) {
System.out.println("Product is expired");
}
else System.out.println("Product is not expired");
}
I understand this question might not be explained well enough so i understand if people wish to downvote it. Any insight or help is much appreciated!
You can make an object of this class and then by using setter function defined in class you can set the value .
Product p1 = new Product();
p1.setId(5);
//This will set the Id to 5
Basically I have multiple classes and I'm trying to get an array of LineItem for each Item that a customer purchases. LineItem includes the UPC, Description, Price, Quantity, SubTotal and Discount which is all stored in a seperate class. I'm trying to get it that when you use the method addItemToSaleList it will add to the array. I need to use an array and not an array list, so I have to copy over the array to a temp array, and then recreate a new array adding to the number the array can store and then recopying it over. I'm stuck getting the array to generate. Below is the code I have
public class Product {
private double price;
private String description;
private String ProductCode;
private DiscountStrategy discoutStrategy;
public Product(double price, String description, String ProductCode, DiscountStrategy discoutStrategy) {
this.price = price;
this.description = description;
this.ProductCode = ProductCode;
this.discoutStrategy = discoutStrategy;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getProductCode() {
return ProductCode;
}
public void setProductCode(String ProductCode) {
this.ProductCode = ProductCode;
}
public DiscountStrategy getDiscountStrategy() {
return discoutStrategy;
}
public void setDiscoutStrategy(DiscountStrategy discoutStrategy) {
this.discoutStrategy = discoutStrategy;
}
}
public class LineItem {
private Product product;
private double quantity;
public LineItem(Product product, double quantity) {
this.product = product;
this.quantity = quantity;
}
//Calculates the Discount Amount whether or not it's a percentage or dollar
//off
public double getDiscountAmount () {
return product.getDiscountStrategy().getDiscount(product.getPrice(), quantity);
}
//Calculates the Subtotal, gets the quantity from the DiscountStrategy and then
//the price from the product
public double getSubTotal() {
return quantity * product.getPrice();
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public double getQuantity() {
return quantity;
}
public void setQuantity(double quantity) {
this.quantity = quantity;
}
public class Receipt {
private LineItem[] lineItem = new LineItem[0];
public Receipt(LineItem[] lineItem) {
this.lineItem = lineItem;
}
public void addProductToTotalSale(LineItem li) {
addItemToSaleList();
}
public void addItemToSaleList() {
LineItem[] tempItemList = new LineItem[lineItem.length + 1];
for (int i = 0; i < tempItemList.length; i++) {
tempItemList[i] = lineItem[i];
}
lineItem = new LineItem[tempItemList.length];
for (int j = 0; j < lineItem.length; j++) {
lineItem[j] = tempItemList[j];
}
}
public LineItem[] getLineItem() {
return lineItem;
}
I would remove addItemToSaleList() and implement addProductToTotalSale(LineItem) like so
public void addProductToTotalSale(LineItem li) {
// Allocate the memory.
LineItem[] tempLineItem = new LineItem[1 + lineItem.length];
// Copy the array.
if (lineItem.length > 0) {
System.arraycopy(lineItem, 0, tempLineItem, 0, lineItem.length);
}
// add the new item to the new slot.
tempLineItem[lineItem.length] = li;
// update the internal array reference.
lineItem = tempLineItem;
}
Next, you should protect your constructor from null;
public Receipt(LineItem[] lineItem) {
// Try and protect from bad calls, removes need to check for nulls in
// add (addProductToTotalSale) routine.
if (lineItem != null) {
this.lineItem = lineItem;
}
}
Because you provide a default 0 sized array your code appears to be safe to continue to include the default constructor. But, you might consider making your Receipt class immutable.
I'm not sure why you are making two new arrays. You only need one...
public void addProductToTotalSale(LineItem li) {
addItemToSaleList();
lineItem[lineItem.length-1] = li;
}
public void addItemToSaleList() {
LineItem[] tempItemList = new LineItem[lineItem.length + 1];
for (int i = 0; i < tempItemList.length; i++) {
tempItemList[i] = lineItem[i];
}
lineItem = tempItemList;
}
I am studying java by myself and I want to get help on exercise which i am doing myself.
The class is called Product which used for representing a product that a small company sells.
It should be possible to store the following information about each product.
The class should have the following methods:
A constructor
A method that returns the units of items in store
A method for deliverance to the store (increases the units of this product)
A method for withdrawal from the store (decreases the units of this product)
Please note that if one of the methods changes the stored items below the order point a message should be printed. It should also be impossible to have a negative amount of items.
I HAVE PROBLEM WITH METHODS. PLEASE TAKE A LOOK MY CODE AND GIVE ME SOME HINTS. I WILL APPRECIATE ALL RESPONDS.
THANK YOU.
Here is my program:
public class Product {
private int productNumber;
private String productName;
private float price;
private int orderPoint;
private int unitsInStore;
private String proDescription;
public Product(int num, String name, float price, int order, int units, String description){
this.productNumber = num;
this.productName = name;
this.price = price;
this.orderPoint = order;
this.unitsInStore = units;
this.proDescription = description;
}
public int getProductNumber() {
return productNumber;
}
public void setProductNumber(int productNumber) {
this.productNumber = productNumber;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public int getOrderPoint() {
return orderPoint;
}
public void setOrderPoint(int orderPoint) {
this.orderPoint = orderPoint;
}
// a method returns the units in store
public int getUnitsInStore() {
return unitsInStore;
}
public void setUnitsInStore(int unitsInStore) {
this.unitsInStore = unitsInStore;
}
public String getProDescription() {
return proDescription;
}
public void setProDescription(String proDescription) {
this.proDescription = proDescription;
}
public int deliveranceToStore(int store){
unitsInStore = unitsInStore + store;
return unitsInStore ++ ;
}
public int withdrawal(int store){
unitsInStore = store - unitsInStore;
return unitsInStore --;
}
}
The deliveranceToStore method isn't correct. Why are you calling the method recursively?
The method can simply be:
public int deliveranceToStore(int store) {
unitsInStore = unitsInStore + store;
return unitsInStore;
}
If there is no need to return the number of units in store with this call, you should have the return type as void (i.e., if updating the count is sufficient):
public void deliveranceToStore(int store) {
unitsInStore = unitsInStore + store;
}
For withdrawal, you need a similar strategy where unitsInStore is updated:
public void withdrawal(int units) {
if(unitsInStore - units >= 0) {
unitsInStore = unitsInStore - units;
} else {
System.out.println("Unable to withdraw. Insufficient units in store.");
}
}
You can also make the withdrawal method return a boolean which tells whether the withdrawal action was successful. The method, in that case, may look like:
public boolean withdrawal(int units) {
if(unitsInStore - units >= 0) {
unitsInStore = unitsInStore - units;
return true;
} else {
System.out.println("Unable to withdraw. Insufficient units in store.");
return false;
}
}
What would be the simplest method to print this array broken down into each mobile phone as a product number, name department etc, and then re print the same information sorted by product name. I have tried a couple different methods and am already passed the turn in date for the assignment but still need to figure it out for upcoming assignment this weekend. When I try to implement the comparator on MobilePhone class it forces me to make it abstract or use #override but I can't figure out where or what to override to make it work because the abstract class causes a multitude of other problems.
package InventoryPro2;
import java.util.*;
class MobilePhone {
private double productNumber; // Variables
private String name;
private String department;
private double unitsInStock;
private double unitPrice;
public MobilePhone() {
this(0.0, "", "", 0.0, 0.0);
}
public MobilePhone(double productNumber, String name, String department,
double unitsInStock, double unitPrice) { //assign variables
this.productNumber = productNumber;
this.name = name;
this.department = department;
this.unitsInStock = unitsInStock;
this.unitPrice = unitPrice;
}
public double getproductNumber() { // retrieve values
return productNumber;
}
public String getname() {
return name;
}
public String getdepartment() {
return department;
}
public double getunitPrice() {
return unitPrice;
}
public double getunitsInStock() {
return unitsInStock;
}
public void setproductNumber(double productNumber) {
this.productNumber = productNumber;
}
public void setname(String name) {
this.name = name;
}
public void setdepartment(String department) {
this.department = department;
}
public void setunitPrice(double unitPrice) {
this.unitPrice = unitPrice;
}
public void setunitsInStock(double unitsInStock) {
this.unitsInStock = unitsInStock;
}
public double gettotalInv() {
return getunitPrice() * getunitsInStock();
}
}
public class InventoryPro2 {
MobilePhone mobilephone = new MobilePhone();
public static void main(String args[]) {
System.out.println("Mobile Phone Inventory Program");
System.out.println();//skips a line
MobilePhone[] phones = new MobilePhone[5];
phones[0] = new MobilePhone();
phones[0].setproductNumber(1);
phones[0].setname("Motorola");
phones[0].setdepartment("Electronics");
phones[0].setunitPrice(150.10);
phones[0].setunitsInStock(98);
phones[1] = new MobilePhone();
phones[1].setproductNumber(2);
phones[1].setname("Samsung");
phones[1].setdepartment("Electronics");
phones[1].setunitPrice(199.99);
phones[1].setunitsInStock(650);
phones[2] = new MobilePhone();
phones[2].setproductNumber(3);
phones[2].setname("Nokia");
phones[2].setdepartment("Electronics");
phones[2].setunitPrice(200.25);
phones[2].setunitsInStock(125);
phones[3] = new MobilePhone();
phones[3].setproductNumber(4);
phones[3].setname("LG");
phones[3].setdepartment("Electronics");
phones[3].setunitPrice(100.05);
phones[3].setunitsInStock(200);
phones[4] = new MobilePhone();
phones[4].setproductNumber(5);
phones[4].setname("IPhone");
phones[4].setdepartment("Electronics");
phones[4].setunitPrice(299.99);
phones[4].setunitsInStock(150);
System.out.println("Order of inventory before sorting:");
System.out.println();
}
}
(Also, what is the best way to take just one piece of information out of each part of the array such as the totalInv and total all of those numbers to print?) Do I have unnecessary code here or have I done everything right thus far? I have to say that learning this coding language in an online format has not been a very enjoyable experience thus far..
Here is how to sort by name
import java.util.Arrays;
import java.util.Comparator;
public class AppInventoryPro2 {
public static void main(String... args) {
System.out.println("Mobile Phone Inventory Program");
System.out.println();// skips a line
MobilePhone[] phones = new MobilePhone[5];
phones[0] = new MobilePhone();
phones[0].setproductNumber(1);
phones[0].setname("Motorola");
phones[0].setdepartment("Electronics");
phones[0].setunitPrice(150.10);
phones[0].setunitsInStock(98);
phones[1] = new MobilePhone();
phones[1].setproductNumber(2);
phones[1].setname("Samsung");
phones[1].setdepartment("Electronics");
phones[1].setunitPrice(199.99);
phones[1].setunitsInStock(650);
phones[2] = new MobilePhone();
phones[2].setproductNumber(3);
phones[2].setname("Nokia");
phones[2].setdepartment("Electronics");
phones[2].setunitPrice(200.25);
phones[2].setunitsInStock(125);
phones[3] = new MobilePhone();
phones[3].setproductNumber(4);
phones[3].setname("LG");
phones[3].setdepartment("Electronics");
phones[3].setunitPrice(100.05);
phones[3].setunitsInStock(200);
phones[4] = new MobilePhone();
phones[4].setproductNumber(5);
phones[4].setname("IPhone");
phones[4].setdepartment("Electronics");
phones[4].setunitPrice(299.99);
phones[4].setunitsInStock(150);
System.out.println("Order of inventory before sorting:");
System.out.println(Arrays.toString(phones));
Arrays.sort(phones, new Comparator<MobilePhone>() {
#Override
public int compare(MobilePhone mp1, MobilePhone mp2) {
return mp1.getname().compareTo(mp2.getname());
}
});
System.out.println("Order of inventory after sorting by name:");
System.out.println(Arrays.toString(phones));
}
}
class MobilePhone {
private double productNumber; // Variables
private String name;
private String department;
private double unitsInStock;
private double unitPrice;
public MobilePhone() {
this(0.0, "", "", 0.0, 0.0);
}
public MobilePhone(double productNumber, String name, String department,
double unitsInStock, double unitPrice) { // assign variables
this.productNumber = productNumber;
this.name = name;
this.department = department;
this.unitsInStock = unitsInStock;
this.unitPrice = unitPrice;
}
public double getproductNumber() { // retrieve values
return productNumber;
}
public String getname() {
return name;
}
public String getdepartment() {
return department;
}
public double getunitPrice() {
return unitPrice;
}
public double getunitsInStock() {
return unitsInStock;
}
public void setproductNumber(double productNumber) {
this.productNumber = productNumber;
}
public void setname(String name) {
this.name = name;
}
public void setdepartment(String department) {
this.department = department;
}
public void setunitPrice(double unitPrice) {
this.unitPrice = unitPrice;
}
public void setunitsInStock(double unitsInStock) {
this.unitsInStock = unitsInStock;
}
public double gettotalInv() {
return getunitPrice() * getunitsInStock();
}
#Override
public String toString() {
return "MobilePhone [productNumber=" + productNumber + ", name=" + name
+ ", department=" + department + ", unitsInStock="
+ unitsInStock + ", unitPrice=" + unitPrice + "]";
}
}
1 - To print content of MobilePhone class: Override default toString method like this:
#Override
public String toString() {
return "MobilePhone [productNumber=" + productNumber +
", name=" + name + ']'; // add more info if needed
}
2 - To allow sorting by name: Have MobilePhone class implement Comparable interface like
this:
class MobilePhone implements Comparable {
...
#Override
public int compareTo(Object o) {
MobilePhone m = (MobilePhone) o;
return (this.name.compareTo(o.name));
}
}
EDIT: To print your array of MobilePhone object you can do:
System.out.printf("Phones: %s%n", Arrays.toString(phones));