How could I fix this NullPointerException and Method chaining in Java? [duplicate] - java

This question already has answers here:
java.lang.NullPointerException with boolean
(5 answers)
Closed 5 years ago.
This is the first time I am using Collections (TreeMap and Treeset). Other parts are working good but I am having NullPointerException. I tried but could not fix after several attempts. I think the problem is in calcTotal, calcSubtotal and calcTax methods. Could anyone help me find my mistake and fix this serious issue? Am I chaining the methods in the right way?
Exception
Exception in thread "main" java.lang.NullPointerException
at posPD.Sale.calcTotal(Sale.java:92)
at posPD.Session.calTotalSession(Session.java:149)
at posTest.LoadStore.loadTheStore(LoadStore.java:52)
at posTest.StoreTest.main(StoreTest.java:163)
Sale.java
package posPD;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
/**
* Sale information and services
*/
public class Sale {
private LocalDateTime dateTime;
private Boolean taxFree;
private BigDecimal amountTendered;
private ArrayList<SaleLineItem> saleLineItems;
private ArrayList<Payment> payments;
private LocalDate date;
public Sale() {
// TODO - implement Sale.Sale
//throw new UnsupportedOperationException();
saleLineItems = new ArrayList<SaleLineItem>();
payments = new ArrayList<Payment>();
//setTaxFree(false);
setDate(date);
setDateTime(dateTime);
//dateTime = LocalDateTime.now();
}
/**
*
* #param taxFree
*/
public Sale(Session session, String taxFree) {
// TODO - implement Sale.Sale
//throw new UnsupportedOperationException();
this();
/*
Boolean boolTax = Boolean.parseBoolean(taxFree);
this.setTaxFree(boolTax);
if (taxFree.equals("N")) {
setTaxFree(false);
} else {
setTaxFree(true);
}
*/
if (taxFree == "Y") {
this.setTaxFree(true);
}
else this.setTaxFree(false);
session.addSale(this);
//setSession(session);
}
/**
*
* #param payment
*/
public void addPayment(Payment payment) {
// TODO - implement Sale.addPayment
//throw new UnsupportedOperationException();
payments.add(payment);
}
/**
*
* #param payment
*/
public void removePayment(Payment payment) {
// TODO - implement Sale.removePayment
//throw new UnsupportedOperationException();
payments.remove(payment);
}
public BigDecimal calcTotal() {
// TODO - implement Sale.calcTotal
//throw new UnsupportedOperationException();
BigDecimal total = new BigDecimal("0.0");
if (this.taxFree) {
total = calcSubTotal().setScale(2, BigDecimal.ROUND_HALF_UP);
return total;
}
else {
total = calcSubTotal().add(this.calcTax().setScale(2, BigDecimal.ROUND_HALF_UP));
return total;
}
}
public BigDecimal calcSubTotal() {
// TODO - implement Sale.calcSubTotal
//throw new UnsupportedOperationException();
BigDecimal subTotal = new BigDecimal("0");
for (SaleLineItem sli: saleLineItems) {
subTotal = subTotal.add(sli.calcSubTotal());
}
System.out.println(subTotal);
return subTotal.setScale(2, RoundingMode.HALF_UP);
}
public BigDecimal calcTax() {
// TODO - implement Sale.calcTax
//throw new UnsupportedOperationException();
BigDecimal tax = new BigDecimal ("0");
if (!getTaxFree()) {
for (SaleLineItem sli : saleLineItems) {
tax = tax.add(sli.calcTax());
}
}
return tax.setScale(2, RoundingMode.HALF_UP);
}
public BigDecimal getTotalPayments() {
// TODO - implement Sale.getTotalPayments
//throw new UnsupportedOperationException();
BigDecimal payment = new BigDecimal("0");
for (Payment p : payments) {
payment = payment.add(p.getAmount());
}
return payment.setScale(2, BigDecimal.ROUND_HALF_UP);
}
public Boolean isPaymentEnough() {
// TODO - implement Sale.isPaymentEnough
//throw new UnsupportedOperationException();
return (calcTotal().compareTo(calcAmtTendered()) <= 0);
}
/**
*
* #param amountTendered
*/
public void calcAmount(BigDecimal amountTendered) {
// TODO - implement Sale.calcAmount
//throw new UnsupportedOperationException();
BigDecimal calcAmount = calcTotal().subtract(calcTotal());
if (calcAmount.compareTo(amountTendered) > 0)
{
calcAmount = amountTendered;
}
System.out.println("Calc Amt : "+calcAmount.setScale(2, BigDecimal.ROUND_HALF_UP));
//return calcAmount.setScale(2, BigDecimal.ROUND_HALF_UP);
}
public BigDecimal calcChange() {
// TODO - implement Sale.calcChange
//throw new UnsupportedOperationException();
//return amountTendered.subtract(getTotalPayments())
return getAmountTendered().subtract(getTotalPayments());
}
public BigDecimal calcAmtTendered() {
// TODO - implement Sale.calcAmtTendered
//throw new UnsupportedOperationException();
//return amountTendered;
BigDecimal amtTendered = new BigDecimal("0");
for (Payment p : payments) {
amtTendered = amtTendered.add(p.getAmtTendered());
}
System.out.println("Payment Amt:"+amtTendered.setScale(2, BigDecimal.ROUND_HALF_UP));
return amtTendered.setScale(2, BigDecimal.ROUND_HALF_UP);
}
/**
*
* #param sli
*/
public void addSaleLineItem(SaleLineItem sli) {
// TODO - implement Sale.addSaleLineItem
//throw new UnsupportedOperationException();
saleLineItems.add(sli);
}
/**
*
* #param sli
*/
public void removeSaleLineItem(SaleLineItem sli) {
// TODO - implement Sale.removeSaleLineItem
//throw new UnsupportedOperationException();
saleLineItems.remove(sli);
}
public BigDecimal getAmountTendered() {
return amountTendered;
}
public void setAmountTendered(BigDecimal amountTendered) {
this.amountTendered = amountTendered;
}
private ArrayList<SaleLineItem> getSaleLineItems() {
return saleLineItems;
}
public String toString() {
// TODO - implement Sale.toString
//throw new UnsupportedOperationException();
String slis = "";
for (SaleLineItem sli : getSaleLineItems()) {
slis += " " +sli.toString() + "\r\n";
}
return "Sale : SubTotal = " +calcSubTotal().toPlainString()
+" Tax = " +calcTax().toPlainString()
+" Total =" +calcTotal().toPlainString()
+" Payment =" +getTotalPayments().toPlainString()
+" Change =" +calcChange().toPlainString() +"\r\n"
+slis;
}
public LocalDateTime getDateTime() {
return dateTime;
}
public void setDateTime(LocalDateTime dateTime) {
this.dateTime = dateTime;
}
public LocalDate getDate() {
return date;
}
public void setDate(LocalDate date) {
this.date = date;
}
public Boolean getTaxFree() {
return taxFree;
}
public void setTaxFree(Boolean taxFree) {
this.taxFree = taxFree;
}
public ArrayList<Payment> getPayments() {
return payments;
}
public void setPayments(ArrayList<Payment> payments) {
this.payments = payments;
}
public void setSaleLineItems(ArrayList<SaleLineItem> saleLineItems) {
this.saleLineItems = saleLineItems;
}
public BigDecimal calcCash()
{
BigDecimal cash = new BigDecimal ("0");
for (Payment p : payments)
{ if (p.hasCash()) cash = cash.add(p.getAmount());}
return cash;
}
}
SaleLineItem.java
package posPD;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
/**
* Items, Quantity details during a sale
*/
public class SaleLineItem {
private int quantity;
private Item item;
//private Sale sale;
private LocalDate date;
private LocalDateTime dateTime;
public SaleLineItem() {
// TODO - implement SaleLineItem.SaleLineItem
//throw new UnsupportedOperationException();
//date = LocalDate.now();
setDateTime(dateTime);
setDate(date);
}
/**
*
* #param itemNumber
* #param quantity
*/
public SaleLineItem(Item item, String quantity) {
// TODO - implement SaleLineItem.SaleLineItem
//throw new UnsupportedOperationException();
//this.itemNumber = Integer.parseInt(itemNumber);
//this.quantity = Integer.parseInt(quantity);
//System.out.println(quantity);
this();
this.item = item;
this.quantity =Integer.parseInt(quantity);
}
public SaleLineItem(Sale sale, Item item, int quantity)
{
this();
this.sale = sale;
setQuantity(quantity);
setItem(item);
sale.addSaleLineItem(this);
getItem().addSaleLineItem(this);
setSale(sale);
System.out.println(sale);
}
/**
*
* #param itemNumber
* #param quantity
*/
public SaleLineItem(Store store, Sale sale, String itemNumber, String quantity) {
// TODO - implement SaleLineItem.SaleLineItem
//throw new UnsupportedOperationException();
this();
setQuantity(Integer.parseInt(quantity));
setItem(store.findItemForNumber(itemNumber));
sale.addSaleLineItem(this);
getItem().addSaleLineItem(this);
setSale(sale);
}
public LocalDateTime getDateTime() {
return dateTime;
}
public void setDateTime(LocalDateTime dateTime) {
this.dateTime = dateTime;
}
public LocalDate getDate() {
return date;
}
public void setDate(LocalDate date) {
this.date = date;
}
public Sale getSale() {
return sale;
}
public void setSale(Sale sale) {
this.sale = sale;
}
private Sale sale;
public int getQuantity() {
return this.quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public Item getItem() {
return this.item;
}
public void setItem(Item item) {
this.item = item;
}
public BigDecimal calcSubTotal() {
// TODO - implement SaleLineItem.calcSubTotal
//throw new UnsupportedOperationException();
//return getItem().calcAmountForDateQty(date, getQuantity());
date = getSale().getDate();
System.out.println(date);
BigDecimal subTotal = getItem().calcTotal(date, getQuantity());
return subTotal;
}
public BigDecimal calcTax() {
// TODO - implement SaleLineItem.calcTax
//throw new UnsupportedOperationException();
BigDecimal amount = calcSubTotal();
BigDecimal taxRate = new BigDecimal(getItem().getTaxRateForDate(getSale().getDate()).toString());
BigDecimal tax = amount.multiply(taxRate).setScale(2, BigDecimal.ROUND_HALF_UP);
return tax;
}
public String toString() {
// TODO - implement SaleLineItem.toString
//throw new UnsupportedOperationException();
try {
LocalDate date = sale.getDate();
} catch (Exception e) {
System.out.println("Exception exists here in SaleLineItem b"+ e.getMessage());
}
return getItem().getNumber()
+" "
+getItem().getDescription()
+ " Qty: "+getQuantity()
+ "Price for Date: "
+"#$"
+ getItem().getPriceForDate(date)
+" $"+calcSubTotal().toString();
}
}
Item.class
package posPD;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
/**
* information about the general details of items in the store
*/
public class Item {
private String number;
private String description;
//private SaleLineItem saleLineItems;
private TaxCategory taxCategory;
private ArrayList<SaleLineItem> saleLineItems;
private TreeMap<String, UPC> upcs;
private TreeSet<Price> prices;
public Item() {
// TODO - implement Item.Item
//throw new UnsupportedOperationException();
upcs = new TreeMap<String, UPC>();
prices = new TreeSet<Price>();
}
/**
*
* #param number
* #param description
*/
public Item(String number, String description) {
// TODO - implement Item.Item
//throw new UnsupportedOperationException();
this();
this.setItemNumber(number);
this.setItemDescription(description);
}
public String getItemNumber() {
return this.number;
}
public void setItemNumber(String number) {
this.number = number;
}
public String getItemDescription() {
return this.description;
}
public void setItemDescription(String description) {
this.description = description;
}
/*
public SaleLineItem getSaleLineItems() {
return saleLineItems;
}
public void setSaleLineItems(SaleLineItem saleLineItems) {
this.saleLineItems = saleLineItems;
}
*/
public ArrayList<SaleLineItem> getSaleLineItems() {
return saleLineItems;
}
public void setSaleLineItems(ArrayList<SaleLineItem> saleLineItems) {
this.saleLineItems = saleLineItems;
}
public TaxCategory getTaxCategory() {
return taxCategory;
}
public void setTaxCategory(TaxCategory taxCategory) {
this.taxCategory = taxCategory;
}
/**
*
* #param price
*/
public void addPrice(Price price) {
// TODO - implement Item.addPrice
//throw new UnsupportedOperationException();
prices.add(price);
}
/**
*
* #param price
*/
public void removePrice(Price price) {
// TODO - implement Item.removePrice
//throw new UnsupportedOperationException();
prices.remove(price);
}
/**
*
* #param upc
*/
public void addUPC(UPC upc) {
// TODO - implement Item.addUPC
//throw new UnsupportedOperationException();
upcs.put(upc.getUPC(), upc);
}
/**
*
* #param upc
*/
public void removeUPC(UPC upc) {
// TODO - implement Item.removeUPC
//throw new UnsupportedOperationException();
upcs.remove(upc.getUPC());
}
public void addSaleLineItem (SaleLineItem sli)
{
if (sli != null)
{
getSaleLineItems().add(sli);
}
}
public void removeSaleLineItem (SaleLineItem sli)
{
if (sli != null)
{
getSaleLineItems().remove(sli);
}
}
/**
*
* #param date
*/
public BigDecimal getPriceForDate(LocalDate date) {
// TODO - implement Item.getPriceForDate
//throw new UnsupportedOperationException();
Price currentPrice = new Price() ;
for (Price price : getPrices()) {
if (price.isEffective(date)) {
currentPrice = price;
}
}
return currentPrice.getPrice();
}
/**
*
* #param date
*/
public BigDecimal getTaxRateForDate(LocalDate date) {
//public String getTaxRateForDate(LocalDate date) {
//return null;
// TODO - implement Item.getTaxRateForDate
//throw new UnsupportedOperationException();
//date = LocalDate.now();
return getTaxCategory().getTaxRateForEffectiveDate(date);
}
public BigDecimal calcTotal(LocalDate saleDate, int quantity) {
// TODO Auto-generated method stub
BigDecimal total;
total = getPriceForDate(saleDate).multiply(new BigDecimal(quantity));
return total;
}
/**
*
* #param date
* #param quantity
*/
public BigDecimal calcAmountForDateQty(LocalDate date, int quantity) {
// TODO - implement Item.calcAmountForDateQty
//throw new UnsupportedOperationException();
BigDecimal total;
total = getPriceForDate(date).multiply(new BigDecimal(quantity));
return total;
}
public TreeMap<String, UPC> getUpcs() {
return upcs;
}
public void setUpcs(TreeMap<String, UPC> upcs) {
this.upcs = upcs;
}
public TreeSet<Price> getPrices() {
return prices;
}
public void setPrices(TreeSet<Price> prices) {
this.prices = prices;
}
public String toString() {
// TODO - implement Item.toString
//throw new UnsupportedOperationException();
String up="";
//if (upcs.isEmpty()) System.out.println("EmptyXXXX");
for(Map.Entry<String, UPC> entry : upcs.entrySet()) {
//String key = entry.getKey();
UPC value = entry.getValue();
//up += key +": " + value;
up += value;
//System.out.println(key + " => " + value);
}
// for prices from tree set
String pp = "";
for (Price p : getPrices()) {
pp += p;
}
return "\n"+"Item No: "+getItemNumber()+ " " + "Item: " + getItemDescription() + " Category: " + getTaxCategory() + " UPC: " + up + " Price: " + pp +"\n";
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
part of LoadStore.Java triggering this exception
package posTest;
import java.time.LocalDate;
import posPD.*;
public class LoadStore {
public LoadStore() {
// TODO Auto-generated constructor stub
}
public void loadTheStore(Store myStore) {
//String list;
//working codes here are removed
System.out.println("\n==============\n");
System.out.println("\nItems");
System.out.println("\n==============\n");
for(Item I : myStore.getItems().values()){
System.out.println(I.toString()+" "
+I.getPriceForDate(LocalDate.now())+" "
+I.getTaxRateForDate(LocalDate.now())
);
}
System.out.println("\n==============\n");
System.out.println("\nSessions");
System.out.println("\n==============\n");
for(Session cashierSession: myStore.getSessions()){
System.out.println("Cashier in Session: "+cashierSession.getCashier().getPerson().getPersonName()+" "+"Register : "+cashierSession.getRegister().getRegisterNumber());
System.out.println("Total : "+cashierSession.calTotalSession());
for(Sale sale : cashierSession.getSales()){
System.out.println(sale);
}
}
System.out.println("StoreCashierIsUsed : "+myStore.findCashierForNumber("1"));
}
}

How did you create Sale instance? Which constructor did you use, Sale(Session session, String taxFree) or Sale()? If you use Sale(), your attribute Boolean taxFree may not be initialized, it can throw NullPointerException when you call:
public BigDecimal calcTotal() {
// TODO - implement Sale.calcTotal
//throw new UnsupportedOperationException();
BigDecimal total = new BigDecimal("0.0");
if (this.taxFree) { // <--- NullPointerException 's here
total = calcSubTotal().setScale(2, BigDecimal.ROUND_HALF_UP);
return total;
}
else {
total = calcSubTotal().add(this.calcTax().setScale(2, BigDecimal.ROUND_HALF_UP));
return total;
}
}
To fix this, use private boolean taxFree; instead.

Related

JavaFX and IntelliJ -- Table Values Won't Populate?

Doing my homework, and trying to get some values to spit out onto a table in IntelliJ right now. I'm following a webinar series, and can't figure out what I'm doing wrong. I try to add a part to the system, but I get an error that "non-static method addPart(classes.Part) cannot be referenced from a static context." Along with three other errors around the same area in my MainApplication.java file.
package project.wfc482project;
import classes.InHouse;
import classes.Outsourced;
import classes.Part;
import classes.Inventory;
import classes.Product;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.io.IOException;
public class MainApplication extends Application {
#Override
public void start(Stage stage) throws IOException {
FXMLLoader fxmlLoader = new FXMLLoader(MainApplication.class.getResource("MainMenu.fxml"));
Scene scene = new Scene(fxmlLoader.load(), 320, 240);
stage.setTitle("C482 Inventory Management System");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
// Sample values, Parts, and Products
InHouse inhouse1 = new InHouse(1, "Tire", 10.99, 10, 0, 20, 125);
InHouse inhouse2 = new InHouse(2, "Strut", 12.99, 27, 0, 30, 124);
Outsourced outsourced1 = new Outsourced(3, "Tubing", 7.50, 5, 0, 15, "Super Parts");
Outsourced outsourced2 = new Outsourced(5, "Lens", 3.50, 22, 0, 25, "Auto Glass");
Inventory.addPart(inhouse1);
Inventory.addPart(inhouse2);
Inventory.addPart(outsourced1);
Inventory.addPart(outsourced2);
launch();
// Call static members
}
}
And here's the Inventory.java page that I am trying to pull from, which pulls from a Parts.java page that I'll throw up here in a sec...
package classes;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
public class Inventory {
private static int partId = 0;
private static int productId = 0;
private static ObservableList<Part> allParts = FXCollections.observableArrayList();
private static ObservableList<Product> allProducts = FXCollections.observableArrayList();
public static ObservableList<Part> getAllParts() {
return allParts;
}
public ObservableList<Product> getAllProducts() {
return allProducts;
}
public void addPart(Part newPart) {
allParts.add(newPart);
}
public void addProduct(Product newProduct) {
allProducts.add(newProduct);
}
public static int getNewPartId() {
return ++partId;
}
public static int getNewProductId() {
return ++productId;
}
public Part lookupPart(int partId) {
Part partFound = null;
for (Part part : allParts) {
if (part.getId() == partId) {
partFound = part;
}
}
return partFound;
}
public ObservableList<Part> lookupPart(String partName) {
ObservableList<Part> partsFound = FXCollections.observableArrayList();
for (Part part : allParts) {
if (part.getName().equals(partName)) {
partsFound.add(part);
}
}
return partsFound;
}
public Product lookupProduct(int productId) {
Product productFound = null;
for (Product product : allProducts) {
if (product.getId() == productId) {
productFound = product;
}
}
return productFound;
}
public ObservableList<Product> lookupProduct(String productName) {
ObservableList<Product> productsFound = FXCollections.observableArrayList();
for (Product product : allProducts) {
if (product.getName().equals(productName)) {
productsFound.add(product);
}
}
return productsFound;
}
public void updatePart(int index, Part selectedPart) {
allParts.set(index, selectedPart);
}
public void updateProduct(int index, Product selectedProduct) {
allProducts.set(index, selectedProduct);
}
public boolean deletePart(Part selectedPart) {
if (allParts.contains(selectedPart)) {
allParts.remove(selectedPart);
return true;
}
else {
return false;
}
}
public boolean deleteProduct(Product selectedProduct) {
if (allProducts.contains(selectedProduct)) {
allProducts.remove(selectedProduct);
return true;
}
else {
return false;
}
}
}
The Part Class:
package classes;
public abstract class Part {
// Declare fields
private int id;
private String name;
private double price;
private int stock;
private int min;
private int max;
// Declare Constructor
public Part(int id, String name, double price, int stock, int min, int max) {
this.id = id;
this.name = name;
this.price = price;
this.stock = stock;
this.min = min;
this.max = max;
}
public Part() {
}
// Setters and Getters
/**
* #return the id
*/
public int getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the price
*/
public double getPrice() {
return price;
}
/**
* #param price the price to set
*/
public void setPrice(double price) {
this.price = price;
}
/**
* #return the stock
*/
public int getStock() {
return stock;
}
/**
* #param stock the stock to set
*/
public void setStock(int stock) {
this.stock = stock;
}
/**
* #return the min
*/
public int getMin() {
return min;
}
/**
* #param min the min to set
*/
public void setMin(int min) {
this.min = min;
}
/**
* #return the max
*/
public int getMax() {
return max;
}
/**
* #param max the max to set
*/
public void setMax(int max) {
this.max = max;
}
}
And the InHouse class:
package classes;
public class InHouse extends Part{
private int machineId;
public InHouse(int id, String name, double price, int stock, int min, int max, int machineId) {
super(id, name, price, stock, min, max);
this.machineId = machineId;
}
public int getMachineId() {
return machineId;
}
public void setMachineId(int machineId) {
this.machineId = machineId;
}
}
I've tried looking up answers to this on here and Reddit, but I'm having a hard time making sense of it all.
I understand that I can't make a part for an abstract class, although that's what the webinar tells me to do (it's more likely that that's what I'm interpreting that as, but I'm turned around and not understanding it).
Change the method Inventory.addPart() to a static method. Change this:
public void addPart(Part newPart) {
allParts.add(newPart);
}
to this
public static void addPart(Part newPart) {
allParts.add(newPart);
}

How can I implement the count 60 seonds for hospital

Who can help me to implement the function if the patient waiting for over 60 seconds the category will change from "low" to "high" and queue behind the newest patient category with "high". Can someone help to me to solve it?
EmergencyRoomSimulator1.java :
package emergencyroomsimulator1;
import java.util.Random;
public class EmergencyRoomSimulator1 {
private static final int WAIT_LIMIT = 1000; // 1000 = 1 second
private PatientQueue pq = new PatientQueue();
private void t() {
try { Thread.sleep(new Random().nextInt(WAIT_LIMIT));
} catch (InterruptedException e) {
}
} // end t method
private void patientArrives(Patient p) {
pq.registerPatient(p);
System.out.println(" ARRIVAL: " + p.getID());
System.out.println(" time arrived: " + p.getTimeArrived());
System.out.println(" category: " + p.getCategory());
System.out.println("------------------------------------");
t();
} // end patientArrives method
public void doctorVisits() {
Patient p = pq.getNextPatient();
System.out.println(" VISIT: " + p.getID());
System.out.println(" time arrived: " + p.getTimeArrived());
System.out.println(" category: " + p.getCategory());
System.out.println("------------------------------------");
t();
} // end doctorVisits method
private void simulate() {
System.out.println("------------------------------------");
System.out.println("ER OPEN");
System.out.println("------------------------------------");
patientArrives(new Patient(100, "high"));
patientArrives(new Patient(101, "low"));
patientArrives(new Patient(102, "low"));
patientArrives(new Patient(103, "high"));
patientArrives(new Patient(104, "high"));
patientArrives(new Patient(105, "low"));
patientArrives(new Patient(106, "low"));
patientArrives(new Patient(107, "high"));
doctorVisits();
doctorVisits();
doctorVisits();
doctorVisits();
doctorVisits();
doctorVisits();
System.out.println("------------------------------------");
System.out.println("ER CLOSED");
System.out.println("------------------------------------");
}
public static void main(String[] args) {
// TODO code application logic here
EmergencyRoomSimulator1 er = new EmergencyRoomSimulator1();
er.simulate();
} // end main
}
Patient.java :
package emergencyroomsimulator1;
import java.util.Date;
public class Patient implements Comparable<Patient> {
protected int id;
protected String category;
protected Date timeArrived;
EmergencyRoomSimulator1 emg;
//protected Date CurrentTime;
// accessors and mutators
public int getID() {
return id;
}
public void setID(int idIn) {
this.id = idIn;
}
public String getCategory() {
return category;
}
public void setCategory(String categoryIn) {
this.category = categoryIn;
}
public java.util.Date getTimeArrived() {
return timeArrived;
}
public int compareTo(Patient other) {
// This code doesn't handle nulls
int result = getCategory().compareTo(other.getCategory());
if (result == 0) {
result = getTimeArrived().compareTo(other.getTimeArrived());
}
return result;
}
// default constructor
public Patient() {
this.id = 0;
this.category = "low"; // unclassified Patients go to the end of the queue
this.timeArrived = new Date();
}
// overloaded constructor
public Patient(int idIn, String categoryIn) {
this.id = idIn;
this.category = categoryIn;
this.timeArrived = new Date();
}
}
PatientComparator.java:
package emergencyroomsimulator1;
import java.util.Comparator;
public class PatientComparator implements Comparator<Patient>{
public int compare(Patient p1, Patient p2) {
int result = p1.getCategory().compareTo(p2.getCategory());
if (result == 0) {
result = p1.getTimeArrived().compareTo(p2.getTimeArrived());
}
return result;
}
}
PatientQueue.java :
package emergencyroomsimulator1;
import java.util.Comparator;
import java.util.PriorityQueue;
public class PatientQueue {
PriorityQueue pq;
// default constructor
public PatientQueue() {
this.pq = new PriorityQueue<Patient>(1, new PatientComparator());
}
public void registerPatient(Patient p) {
this.pq.add(p);
} // end registerPatient method
public Patient getNextPatient() {
return (Patient) this.pq.poll();
} // end getNextPatient method
}

My java class validation is not working why?

If the quantity is not positive it should be set to 0.
If the price per item is not positive it should be set to 0.0.
Hwever when I enter a negative number it keeps setting my variable negative and not Zero.
This is my class package com.company;
/**
* Created by juliodiaz on 5/7/16.
*/
public class Invoice {
private String partNumber;
private String partDescription;
private int partQuantity;
private double partPrice;
public Invoice(String partNumber, String partDescription, int partQuantity, double partPrice) {
this.partNumber = partNumber;
this.partDescription = partDescription;
this.partQuantity = partQuantity;
this.partPrice = partPrice;
}
public String getPartNumber() {
return partNumber;
}
public void setPartNumber(String partNumber) {
this.partNumber = partNumber;
}
public String getPartDescription() {
return partDescription;
}
public void setPartDescription(String partDescription) {
this.partDescription = partDescription;
}
public int getPartQuantity() {
return partQuantity;
}
public void setPartQuantity(int partQuantity) {
this.partQuantity = partQuantity;
}
public double getPartPrice() {
return partPrice;
}
public void setPartPrice(double partPrice) {
this.partPrice = partPrice;
}
public double invoiceAmountMethod(double partPrice, int partQuantity) {
if (partQuantity < 0 || partPrice < 0.0) {
this.partQuantity = 0;
return partPrice * partQuantity;
}
else
return partPrice * partQuantity;
}
}
//Main method
package com.company;
public class Main {
public static void main(String[] args) {
// write your code here
Invoice myTruck = new Invoice("A101", "Wheels", -2, 100.00);
System.out.println(myTruck.getPartDescription());
System.out.println(myTruck.getPartNumber());
System.out.println(myTruck.getPartQuantity());
System.out.println(myTruck.getPartPrice());
double price = myTruck.getPartPrice();
int quantity = myTruck.getPartQuantity();
System.out.println("The total cost is " + myTruck.invoiceAmountMethod(price, quantity));
}
}
OUTPUT
Wheels
A101
-2
100.0
The total cost is -200.0
You're assigning:
this.partQuantity = 0;
but you return:
return partPrice * partQuantity;
(the parameters that were passed to the method).
you can fix it by returning:
return this.partPrice * this.partQuantity;
and you really shouldn't pass any parameters to this method.
Here is what you need.
public double invoiceAmountMethod(double partPrice, int partQuantity) {
return (partQuantity < 0 || partPrice < 0.0)?0.0:partPrice * partQuantity;
}

Similar Objects Quantity

I have an assignment to make this Restaurant Program. it Consists of an Order Class a product class and the main class. Order has an ArrayList to hold the products. I create an instance of the Order and then I add items through my main method.A product has a name(string) a bar-code(string), and a price(float).
Then I have to output a receipt.But what if a customer orders more of one product? Do I instantiate everything one by one? Is a second Beer Product independent? Should I hold quantities somehow? If I want to add a second beer I have to create a new product Beer2 etc? I don't know beforehand how many products each order will hold and the quantity of each so Is this way of instantiating proper? Thanks
Note: it is still incomplete as I want to deal with this before I move on.
import java.util.Date;
public class MyRestaurantTester {
public static void main(String[] args) {
Date currentDate = new Date();
Paraggelia order1 = new Paraggelia(currentDate,"11B");
Product Beer = new Product("Amstel","111222",1.20f);
Product Beef = new Product("Pork Beef","333444",8.50f);
order1.add(Beer);
order1.add(Beef);
System.out.println(order1.getReceipt(30f));
}
}
Order Class(nevermind the name Paraggelia I gave it)
import java.util.ArrayList;
import java.util.Date;
/*Notes to self:
* -Work on Comments
* -Javadocs maybe?
* -try to optimize the rough code.
*/
/*Order class*/
public class Paraggelia {
private Date orderDate;
private String tableNumber;
private int customerCount;
private ArrayList<Product> listOfItems;
/*Constructor(s)*/
Paraggelia(Date orderDate,String tableNumber){
this.orderDate=orderDate;
this.tableNumber=tableNumber;
this.listOfItems = new ArrayList<Product>();
}
/*Add && Delete Products from the Order class*/
public void add(Product p){
if(p == null)
{
throw new IllegalArgumentException();
}else{
listOfItems.add(p);
}
}
public void delete(Product p){
if(p == null)
{
throw new IllegalArgumentException();
}
else
{
listOfItems.remove(p);
}
}
/** Calculates and returns the total price
* Usually called directly as a parameter of getReceipt function
* */
public static float getTotalPrice(){
return 0;
}
/** Creates and returns the final Receipt!
* -Display must consist of:
* Item$ - BarCode# - Item Amount#
* Total Price#
* Table Number#
*/
public String getReceipt(float totalPrice){
StringBuilder receipt = new StringBuilder();
for(int i =0; i<this.listOfItems.size();i++){
receipt.append(listOfItems.get(i).getName());
receipt.append("\n");
}
return new String(receipt);
}
/*Getters && Setters */
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
public String getTableNumber() {
return tableNumber;
}
public void setTableNumber(String tableNumber) {
this.tableNumber = tableNumber;
}
public int getCustomerCount() {
return customerCount;
}
public void setCustomerCount(int customerCount) {
this.customerCount = customerCount;
}
}
Product Class:
public class Product {
private String Name;
private String barCode;
private float sellingPrice;
/*Constructors: */
Product(){}
Product(String Name,String barCode,float sellingPrice){
this.Name=Name;
this.barCode=barCode;
this.sellingPrice=sellingPrice;
}
/*Getters & Setters*/
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getBarCode() {
return barCode;
}
public void setBarCode(String barCode) {
this.barCode = barCode;
}
public float getSellingPrice() {
return sellingPrice;
}
public void setSellingPrice(float sellingPrice) {
this.sellingPrice = sellingPrice;
}
}
Instead of ArrayList ( List ) you can use Map ( HashMap for example )
MyRestaurantTester
public class MyRestaurantTester {
public static void main(String[] args) {
Date currentDate = new Date();
Paraggelia order1 = new Paraggelia(currentDate,"11B");
Product Beer = new Product("Amstel","111222",1.20f);
Product Beef = new Product("Pork Beef","333444",8.50f);
order1.add(Beer, 1);
order1.add(Beef, 5);
System.out.println(order1.getReceipt(30f));
}
}
Paraggelia
class Paraggelia {
private Date orderDate;
private String tableNumber;
private int customerCount;
private Map<Product, Integer> listOfItems;
/*Constructor(s)*/
Paraggelia(Date orderDate,String tableNumber){
this.orderDate=orderDate;
this.tableNumber=tableNumber;
this.listOfItems = new HashMap<Product, Integer>();
}
/*Add && Delete Products from the Order class*/
public void add(Product p, int quantity){
if(p == null)
{
throw new IllegalArgumentException();
}else{
listOfItems.put(p, quantity);
}
}
public void delete(Product p){
if(p == null)
{
throw new IllegalArgumentException();
}
else
{
listOfItems.remove(p);
}
}
/** Calculates and returns the total price
* Usually called directly as a parameter of getReceipt function
* */
public static float getTotalPrice(){
return 0;
}
/** Creates and returns the final Receipt!
* -Display must consist of:
* Item$ - BarCode# - Item Amount#
* Total Price#
* Table Number#
*/
public String getReceipt(float totalPrice){
StringBuilder receipt = new StringBuilder();
for(Map.Entry<Product,Integer> entry : this.listOfItems.entrySet()) {
Product product = entry.getKey();
Integer quantity = entry.getValue();
receipt.append(product.getName() + " " + quantity);
receipt.append("\n");
}
return new String(receipt);
}
/*Getters && Setters */
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
public String getTableNumber() {
return tableNumber;
}
public void setTableNumber(String tableNumber) {
this.tableNumber = tableNumber;
}
public int getCustomerCount() {
return customerCount;
}
public void setCustomerCount(int customerCount) {
this.customerCount = customerCount;
}
}
OUTPUT:
Pork Beef 5
Amstel 1
Three basic approaches come to mind:
Instantiate each product individually
Instead of ArrayList, have another structure that can associate items with quantities; or,
Make a class Article, which belongs to a Product: Product beerProduct = new Product("beer", "0129", 1.37); Article beer = new Article(beerProduct), beer2 = new Article(beerProduct).
The first solution gives you a lot of flexibility (e.g. to discount individual articles for, say, being damaged). The second solution is more economical with objects. The third one captures the intuition that all the Heineken bottles are the same. It is really up to what you want to do - both approaches are equally valid, for some purpose.

Yield calculation

In my portfolio application I have a table with stock title and portfolio weight. For each stock title I'm downloading prices for a specific time window. Now I'm trying to calculate the average portfolio rate return.
Formula per day:
Ypf(d) = (W1 * Y1(d)) + (W2 * Y2(d)) + … + (Wn * Yn(d))
Formula Portfolio:
(Ypf(1) + Ypf(2) + ... + Ypf(dn)) / n
> W1 = weight of 1st stock in table
> W2 = weight of 2nd stock in table
> Y1 = yield of 1st stock in table
> Y2 = yield of 2nd stock in table
> d = current day n = total days
I am stuck here and seeking for help....
public void calcAvgYield() {
for (Stock s : pfTable.getItems()) {
// get list of prices for stock title
List<Double> vl = s.getValue();
// new list for calculated yield
List<Double> yl = null;
// get weight for stock title
int w = s.getWeight();
// get list size
int i = vl.size()-1;
// calculate yield for each day and fill new list with results
while (i > 0) {
yl.add(((s.getValue().get(i) - s.getValue().get(i-1)) / s.getValue().get(i-1)) * 100);
i--;
}
}
}
Stock class:
public class Stock {
private final SimpleStringProperty symbol = new SimpleStringProperty();
private final SimpleIntegerProperty weight = new SimpleIntegerProperty();
private List<Double> value = new ArrayList<Double>();
private List<String> date = new ArrayList<String>();
public String getSymbol() {
return symbol.get();
}
public void setSymbol(String symbol) {
this.symbol.set(symbol);
}
public Integer getWeight() {
return weight.get();
}
public void setWeight(Integer weight) {
this.weight.set(weight);
}
public List<Double> getValue() {
return value;
}
public void setValue(ArrayList<Double> value) {
this.value = value;
}
}
Thanks.
Java's an object-oriented language. Why don't you use objects and encapsulation to better advantage? I think your problem is that you haven't abstracted the problem very well.
I'd expect to see a Stock class, not Lists of doubles. A Portfolio would have a Map of stock, shares pairs.
A Stock might have a Map of date, value pairs.
How do you calculate the weights? Are they fractions of shares in the Portfolio?
Let the Portfolio calculate the current rate of return in a method by iterating over its Map of Stocks.
Here's how I'd do it. I think there are still subtleties to be sorted out with number of shares, because your position can evolve over time. A Map of Stock and shares, with Stock carrying prices over time, is insufficient. But this will give you the idea.
Stock.java
package stock;
import utils.StringUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Stock abstraction
* #author Michael
* #link https://stackoverflow.com/questions/24417246/yield-calculation/24430415
* #since 6/26/2014 6:22 PM
*/
public class Stock implements Comparable<Stock> {
private final String symbol;
private final String companyName;
private Map<Date, Double> prices;
public Stock(String symbol, String companyName) {
if (StringUtils.isBlankOrNull(symbol)) throw new IllegalArgumentException("symbol cannot be blank or null");
if (StringUtils.isBlankOrNull(companyName)) throw new IllegalArgumentException("company name cannot be blank or null");
this.symbol = symbol;
this.companyName = companyName;
this.prices = new ConcurrentHashMap<Date, Double>();
}
public String getSymbol() {
return symbol;
}
public String getCompanyName() {
return companyName;
}
public void addPrice(Date date, double price) {
if (date == null) throw new IllegalArgumentException("date cannot be null");
if (price < 0.0) throw new IllegalArgumentException("price cannot be negative");
this.prices.put(date, price);
}
public void removePrice(Date date) {
if (date != null) {
this.prices.remove(date);
}
}
public synchronized Double getPrice(Date date) {
double price = 0.0;
if (this.prices.containsKey(date)) {
price = this.prices.get(date);
} else {
price = interpolatePrice(date);
}
return price;
}
private Double interpolatePrice(Date date) {
double price = 0.0;
if (this.prices.size() > 0) {
List<Date> dates = new ArrayList<Date>(this.prices.keySet());
Collections.sort(dates, new DateComparator());
if (date.before(dates.get(0))) {
price = this.prices.get(dates.get(0));
} else if (date.after(dates.get(dates.size()-1))) {
price = this.prices.get(dates.get(dates.size()-1));
} else {
for (int i = 1; i < dates.size(); ++i) {
if (dates.get(i).after(date)) {
Date d1 = dates.get(i-1);
double p1 = this.prices.get(d1);
Date d2 = dates.get(i);
double p2 = this.prices.get(d2);
double fraction = ((double)(date.getTime()-d1.getTime())/(d2.getTime()-d1.getTime()));
price = p1 + fraction*(p2-p1);
}
}
}
}
return price;
}
public boolean hasDate(Date date) {
return this.prices.containsKey(date);
}
public int getNumPrices() {
return this.prices.size();
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Stock stock = (Stock) o;
return symbol.equals(stock.symbol);
}
#Override
public int hashCode() {
return symbol.hashCode();
}
#Override
public int compareTo(Stock other) {
return this.symbol.compareTo(other.symbol);
}
#Override
public String toString() {
return this.symbol;
}
}
class DateComparator implements Comparator<Date> {
#Override
public int compare(Date that, Date another) {
if (that.before(another)) {
return -1;
} else if (that.after(another)) {
return +1;
} else {
return 0;
}
}
}
Portfolio.java:
package stock;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Portfolio is a collection of Stocks
* #author Michael
* #link https://stackoverflow.com/questions/24417246/yield-calculation/24430415
* #since 6/26/2014 6:31 PM
*/
public class Portfolio {
private Map<Stock, Integer> stocks;
public Portfolio() {
this.stocks = new ConcurrentHashMap<Stock, Integer>();
}
public void addStock(Stock stock, int numShares) {
if (stock == null) throw new IllegalArgumentException("stock cannot be null");
this.stocks.put(stock, numShares);
}
public void addStock(Stock stock) {
addStock(stock, 1);
}
public void updateShares(Stock stock, int numShares) {
if (numShares <= 0) throw new IllegalArgumentException("numShares must be greater than zero");
if (stock != null) {
this.stocks.put(stock, numShares);
}
}
public void removeStock(Stock stock) {
if (stock != null) {
this.stocks.remove(stock);
}
}
public boolean containsSymbol(String symbol) {
return this.getPortfolioSymbols().contains(symbol);
}
public int getNumShares(String symbol) {
int numShares = 0;
if (this.getPortfolioSymbols().contains(symbol)) {
numShares = this.stocks.get(new Stock(symbol, "Dummy Company Name"));
}
return numShares;
}
public int getNumStocks() {
return this.stocks.size();
}
public List<String> getPortfolioSymbols() {
List<String> symbols = new ArrayList<String>(this.stocks.size());
for (Stock stock : stocks.keySet()) {
symbols.add(stock.getSymbol());
}
Collections.sort(symbols);
return symbols;
}
public double calculateValue(Date date) {
double value = 0.0;
if (date != null) {
for (Stock stock : this.stocks.keySet()) {
value += stock.getPrice(date)*this.stocks.get(stock);
}
}
return value;
}
}
Here's how you unit test a Java class. I've also written a JUnit test for Portfolio, but I won't post it now.
StockTest.java:
package stock;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* PortfolioTest JUnit test for Portfolio
* #author Michael
* #link https://stackoverflow.com/questions/24417246/yield-calculation/24430415
* #since 6/26/2014 8:33 PM
*/
public class PortfolioTest {
private static final String DATE_PATTERN = "yyyy-MMM-dd";
private static final DateFormat DATE_FORMAT;
private static final double TOLERANCE = 0.001;
static {
DATE_FORMAT = new SimpleDateFormat(DATE_PATTERN);
DATE_FORMAT.setLenient(false);
}
private Portfolio portfolio;
#Before
public void setUp() throws ParseException {
this.portfolio = new Portfolio();
Stock testStock = new Stock("AAPL", "Apple Inc");
testStock.addPrice(DATE_FORMAT.parse("2014-Jun-02"), 89.807);
testStock.addPrice(DATE_FORMAT.parse("2014-Jun-04"), 92.117);
this.portfolio.addStock(testStock, 100);
testStock = new Stock("ORCL", "Oracle Corporation");
testStock.addPrice(DATE_FORMAT.parse("2014-Jun-02"), 41.97);
testStock.addPrice(DATE_FORMAT.parse("2014-Jun-04"), 41.70);
this.portfolio.addStock(testStock, 1000);
}
#Test
public void testPortfolio_Setup() {
List<String> expectedSymbols = Arrays.asList("AAPL", "ORCL");
Assert.assertEquals(expectedSymbols, this.portfolio.getPortfolioSymbols());
for (String symbol : expectedSymbols) {
Assert.assertTrue(this.portfolio.containsSymbol(symbol));
}
Assert.assertEquals(expectedSymbols.size(), portfolio.getNumStocks());
Assert.assertFalse(this.portfolio.containsSymbol("UTX"));
}
#Test
public void testRemoveStock_ContainsStock() {
int expectedSize = 2;
Assert.assertEquals(expectedSize, portfolio.getNumStocks());
Stock testStock = new Stock("AAPL", "Apple Inc");
this.portfolio.removeStock(testStock);
Assert.assertEquals(expectedSize - 1, portfolio.getNumStocks());
}
#Test
public void testRemoveStock_DoesNotContainStock() {
int expectedSize = 2;
Assert.assertEquals(expectedSize, portfolio.getNumStocks());
Stock testStock = new Stock("UTXL", "United Technologies Corporation");
this.portfolio.removeStock(testStock);
Assert.assertEquals(expectedSize, portfolio.getNumStocks());
}
#Test
public void testGetNumShares_ContainsSymbol() {
Map<String, Integer> expected = new HashMap<String, Integer>() {{
put("AAPL", 100);
put("ORCL", 1000);
}};
for (String symbol : expected.keySet()) {
Assert.assertTrue(expected.get(symbol) == portfolio.getNumShares(symbol));
}
}
#Test
public void testGetNumShares_DoesNotContainSymbol() {
Assert.assertEquals(0, portfolio.getNumShares("UTX"));
}
#Test
public void testCalculateValue_BeforeFirstDate() throws ParseException {
Date testDate = DATE_FORMAT.parse("2014-Jun-02");
double expected = 89.807*100 + 41.97*1000;
double actual = portfolio.calculateValue(testDate);
Assert.assertEquals(expected, actual, TOLERANCE);
}
#Test
public void testCalculateValue_AfterLastDate() throws ParseException {
Date testDate = DATE_FORMAT.parse("2014-Jul-04");
double expected = 92.117*100 + 41.70*1000;
double actual = portfolio.calculateValue(testDate);
Assert.assertEquals(expected, actual, TOLERANCE);
}
#Test
public void testCalculateValue_Interpolate() throws ParseException {
Date testDate = DATE_FORMAT.parse("2014-Jun-03");
double expected = 90.962*100 + 41.835*1000;
double actual = portfolio.calculateValue(testDate);
Assert.assertEquals(expected, actual, TOLERANCE);
}
#Test
public void testUpdateShares() {
Stock testStock = new Stock("ORCL", "Oracle Corporation");
Assert.assertEquals(1000, this.portfolio.getNumShares("ORCL"));
this.portfolio.updateShares(testStock, 10);
Assert.assertEquals(10, this.portfolio.getNumShares("ORCL"));
}
}
I think you need to initialize your list. Try:
List<Double> yl = new ArrayList<Double>();
Currently, it's null, which may be giving you the problem.
Put this
List<Double> yl = null;
before the
for (Stock s : pfTable.getItems()) {
loop.

Categories