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;
}
Related
I'm doing my short project that acts as a type of electronic store inventory. Here's the list of item's number, description, quantity, and price from the text file:
65321,Tablet,54,150.00
91524,Monitors,24,125.50
25013,Printers,30,65.75
32841,Router,67,90.15
53214,Modem,50,50.50
26442,Hard Drive,14,40.89
30224,Power Supplies,44,125.44
41557,CPU,39,149.54
71561,Headphones,40,75.24
This is what I've done so far:
InventoryCalculate.java
ArrayList<BookItem> inventory = new ArrayList<>();
BufferedReader inFile = new BufferedReader(new FileReader("C:\\Users\\Documents\\Data\\stock.txt"));
String line;
line = input.nextLine();
String[] tokens = line.split(",");
int itemNumber = Integer.parseInt(tokens[0]);
String description = tokens[1];
int quantity = Integer.parseInt(tokens[2]);
double unitCost = Double.parseDouble(tokens[3]);
System.out.println("Inventory Item");
System.out.println("Number Description Quantity Unit Price Value");
Inventorystock.java
public class InventoryItem {
private int itemNumber;
private String description;
private int quantity;
private double unitCost;
public InventoryItem(int itemNumber, String description, int quantity, double unitCost) {
this.itemNumber = itemNumber;
this.description = description;
this.quantity = quantity;
this.unitCost = unitCost;
}
public int getItemNumber() {
return itemNumber;
}
public void setItemNumber(int itemNumber) {
this.itemNumber = itemNumber;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public double getUnitCost() {
return unitCost;
}
public void setUnitCost(double unitCost) {
this.unitCost = unitCost;
} }
I'm having trouble figuring out how to get the total value of each item. Here what I need to see the result look like this
Expected output:
Number Description Quantity Unit Price Value
65321 Tablets 54 150.00 8,100.00
91524 Monitors 24 125.50 3,012.00
25013 Printers 30 65.75 1,972.50
32841 Routers 67 90.15 6,040.05
53214 Modems 50 50.50 2,525.00
26442 Hard Drives 14 40.89 572.46
30224 Power Supplies 44 125.44 5,519.36
41557 CPU 39 149.54 5,832.06
71561 Headphones 40 75.24 3,009.60
Create a method that takes the total quantity of the item, multiplies it by the unit cost and then returns the result. Add the following code to your InventoryItem class.
public double getTotalValueOfItem()
{
return unitCost * quantity;
}
Add another property in InventoryItem class as totalValue and add setter, getter methods with your logic. The best way to keep total value calculation in the method that you're displaying details.
public class InventoryItem {
private int itemNumber;
private String description;
private int quantity;
private double unitCost;
private double totalValue;
public InventoryItem(int itemNumber, String description, int quantity, double unitCost) {
this.itemNumber = itemNumber;
this.description = description;
this.quantity = quantity;
this.unitCost = unitCost;
}
public int getItemNumber() {
return itemNumber;
}
public void setItemNumber(int itemNumber) {
this.itemNumber = itemNumber;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public double getUnitCost() {
return unitCost;
}
public void setUnitCost(double unitCost) {
this.unitCost = unitCost;
}
public double getTotalValue() {
return totalValue;
}
public void setTotalValue(int quantity, double unitCost) {
this.totalValue = (double) quantity * unitCost;
}
}
You can add this method to print the item details
public void printDetails() {
System.out.println("Number\tDescription\tQuantity\tUnit Price\tValue");
List < InventoryItem > inventoryItemsList = new ArrayList < InventoryItem > ();
inventoryItemsList.add(new InventoryItem(1, "description 1", 2, 50.0));
inventoryItemsList.add(new InventoryItem(2, "description 2", 3, 40.0));
for (InventoryItem item: inventoryItemsList) {
System.out.println(item.itemNumber + "\t" + item.description + "\t" + item.quantity + "\t" + item.unitCost + "\t" + item.totalValue);
}
}
You can store the details of inventory items as a String or as a List as demonstrated in printDetails method. Hope this "printDetails" method solved your issue. If you really want to store item details as a string then you can store all item details into a string array.
Make sure to import required libraries and model classes in following way.
import java.util.List;
import java.util.ArrayList;
import <package>.InventoryItem;
I am making a text-based game on JavaFX, and after I hit a tree, I want to get Oak logs.
I have already built my inventory, and I have put default items in it such as Water, Bread, etc.
I am trying to add my Oak Logs to my inventory, but nothing is working.
Here is a part of my code:
Item ItemList[] = {new Bread(), new OakLog()};
Optional<ButtonType> result = alert.showAndWait();
if(result.get() == buttonTypeOak) {
woodcuttingXP = woodcuttingXP + oakXP;
dialogue.appendText("You swing at an Oak tree. + " + oakXP + "XP.\n");
dialogue.appendText("You gathered 1 log.\n");
mainCharacter.getInventory().add(new OakLog());
}
Here is my Item Class:
package game;
public class Item {
private String name;
private int weight;
private int quantity;
private int value;
private String description;
public Item(String name, int value, String description) {
this.name = name;
this.value = value;
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String toString() {
return getName();
}
}
And finally, here is my Character class:
package game;
import java.util.ArrayList;
import beverages.Water;
import items.OakLog;
import rawFood.Bread;
public class Character {
private String name;
private int hydrationLevel;
private int healthLevel;
private int hungerLevel;
private int woodcuttingLevel;
public int getWoodcuttingLevel() {
return woodcuttingLevel;
}
public void setWoodcuttingLevel(int woodcuttingLevel) {
this.woodcuttingLevel = woodcuttingLevel;
}
public int getHungerLevel() {
return hungerLevel;
}
public void setHungerLevel(int hungerLevel) {
this.hungerLevel = hungerLevel;
}
private ArrayList<Item> inventory = new ArrayList<Item>();
public ArrayList<Item> getInventory() {
return inventory;
}
public void setInventory(ArrayList<Item> inventory) {
this.inventory = inventory;
}
//creates a person with two basic items
public Character(String name){
this.name = name;
this.hydrationLevel = 100;
this.healthLevel = 100;
this.hungerLevel = 100;
this.woodcuttingLevel = 1;
addToInventory (new Bread());
addToInventory (new OakLog());
addToInventory (new Water());
}
//GETTERS AND SETTERS
public String getName() {
return name;
}
public int getHydrationLevel() {
return hydrationLevel;
}
public void setHydrationLevel(int hydrationLevel) {
this.hydrationLevel = hydrationLevel;
}
public int getHealthLevel() {
return healthLevel;
}
public void setHealthLevel(int healthLevel) {
this.healthLevel = healthLevel;
}
//END GETTERS AND SETTERS
/*Method Name: eat()
*Method Inputs: a piece of food
*Method Purpose: Will allow the user to eat food
*/
public Item getItemFromInventory(int index){
Item item = inventory.get(index);
return item;
}
public void addToInventory(Item item){
if(inventory.contains(item)){
item.setQuantity(item.getQuantity()+1);
}
else{
item.setQuantity(1);
inventory.add(item);
}
}
public String toString(){
return "Character Stats:\nName:" + getName() + "\nHydration: " + getHydrationLevel() + "\nHealth: " + getHealthLevel() + "\nWoodcutting: " + getWoodcuttingLevel();
}
}
In your code, you have:
if(inventory.contains(item)){
item.setQuantity(item.getQuantity()+1);
}
This just updates the quantity of the local variable item in the method, not the item in the inventory.
New to Java.
I have a txt file:
hat, 20, 1
pants, 50, 45
shoes, 100, 10
In one class called Goods I have been able to read it, split it using delimiter, add it to an ArrayList.
I have another class called GoodsList where I will be creating an ArrayList which should have the above as an object that I can use if the user requests it. Thanks
I think you are asking about java generics.
If so, create your Goods class since you need to access it as an object via the ArrayList.
public Class Goods implements Serializable {
private String goodName;
private double price;
private int quantity;
public String getGoodName() {
return goodName;
}
public void setGoodName(String goodName) {
this.goodName = goodName;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
and then Write your GoodsList class to create the list with Goods object you set:
public class GoodsList {
public static void main(String args[]) {
Goods g = new Goods();
Goods g2 = new Goods();
Goods g3 = new Goods();
g.setGoodName("hat");
g.setQuantity(50);
g.setPrice(100.00);
g2.setGoodName("pants");
g2.setQuantity(50);
g2.setPrice(100.00);
g3.setGoodName("shoes");
g3.setQuantity(50);
g3.setPrice(100.00);
List < Goods > goodsList = new ArrayList < Goods > ();
goodsList.add(g);
goodsList.add(g2);
goodsList.add(g3);
//printing goods:
for (Goods g: goodsList) {
System.out.println(g.getGoodName() + "," + g.getQuantity() + "," + g.getPrice());
}
}
}
is that what you're looking for?
Are you looking for something like:
public class FileReaderExample
{
public class Goods
{
private String goodName = null;
private String price = null;
private String quantity = null;
public Goods(String goodName ,String price,String quantity)
{
this.goodName = goodName;
this.price = price;
this.quantity = quantity;
}
public String getGoodName()
{
return goodName;
}
public void setGoodName(String goodName)
{
this.goodName = goodName;
}
public String getPrice()
{
return price;
}
public void setPrice(String price)
{
this.price = price;
}
public String getQuantity()
{
return quantity;
}
public void setQuantity(String quantity)
{
this.quantity = quantity;
}
}
private ArrayList<Goods> populateGoods()
{
ArrayList<Goods> goodsList = new ArrayList<Goods>();
File file = new File("d:\\text.txt");
try
{
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null)
{
String[] itemsOnLine = line.trim().split(",");
goodsList.add(new Goods(itemsOnLine[0],itemsOnLine[1],itemsOnLine[2]));
}
}
catch (IOException e)
{
e.printStackTrace();
}
return goodsList;
}
public static void main(String[] args)
{
FileReaderExample fileReaderExample = new FileReaderExample();
ArrayList<Goods> goodsList = fileReaderExample.populateGoods();
for (Goods goods : goodsList)
{
System.out.println(goods.getGoodName());
}
}
}
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.
I'm trying to write a very simple program that produces an invoice for an item purchased.
I have a driver class with my setters and getters, and my object class which is supposed to call them. However, when I print out the invoice, it just produces null responses for everything.
Here is my driver class:
public class Invoice {
private String partNumber; //part number of item
private String description; //description of item
private int quantity; //quantity being purchased
private double itemPrice; //price of item
//constructor
public Invoice(String partNumber, String description, int quantity, double itemPrice) {
partNumber = partNumber;
description = description;
if (quantity < 0) {
quantity = 0;
}
if (itemPrice < 0.0) {
itemPrice = 0.0;
}
}
public void setPartNumber(String number) {
partNumber = number; //store the partNumber
}
public void setDescription(String description) {
description = description;//store the description
}
public void setQuantity(int quantity) {
quantity = quantity;//store the quantity
}
public void setItemPrice(double price) {
itemPrice = price;//store the itemPrice
}
public String getPartNumber() {
return partNumber;//retrieve the partNumber
}
public String getDescription() {
return description;//retrieve the description
}
public int getQuantity() {
return quantity;//retrieve the quantity
}
public double getItemPrice() {
return itemPrice;//retrieve the itemPrice
}
//get price for item purchased.
public double getInvoiceAmount(double amount) {
amount = itemPrice * quantity;
if (amount < 0) {
amount = 0.0;
}
return amount;
}
}
And here is my object class:
public class InvoiceTest {
public static void main(String[] args) {
Invoice invoice1 = new Invoice ("0001", "Hammer: used to hit nails.", 1, 10.0);
System.out.println("Item purchased: " + invoice1.getPartNumber() +
"\n Description: " + invoice1.getDescription() +
"\n Amount:" + invoice1.getQuantity() +
"\n price: " + invoice1.getQuantity());
System.out.println();
System.out.println("Total price: " + invoice1.getInvoiceAmount(amount));
}
}
You forgot to assign the variables to the fields in constructor. Use this keyword to refer to the class fields:
public Invoice(String partNumber, String description, int quantity, double itemPrice) {
//here's an example
//partNumber = partNumber
this.partNumber = partNumber;
//description = description;
this.description = description;
//similar for other assignments inside the constructor...
}
You must also do this in your setters as well:
public void setPartNumber(String partNumber) {
this.partNumber = partNumber; //store the partNumber
}
Your class's member fields are not being initialized as you intended, because of this:
public Invoice(String partNumber, String description, int quantity, double itemPrice)
{
partNumber = partNumber;
Here, partNumber refers to the function argument, not the member field. To set the member field, use this.partNumber = partNumber.
Your setters are not setting the values into the object instance, you need to make changes like below
public Invoice(String partNumber, String description, int quantity,
double itemPrice) {
this.partNumber = partNumber;
this.description = description;
this.quantity = quantity;
if (this.quantity < 0) {
this.quantity = 0;
}
this.itemPrice = itemPrice;
if (this.itemPrice < 0.0) {
this.itemPrice = 0.0;
}
}
public void setPartNumber(String number) {
this.partNumber = number; //store the partNumber
}
public void setDescription(String description) {
this.description = description;//store the description
}
public void setQuantity(int quantity) {
this.quantity = quantity;//store the quantity
}
public void setItemPrice(double price) {
this.itemPrice = price;//store the itemPrice
}