I'm still fairly new in learning Java and I'm in need of a way to put every object that is constructed from a certain class into an ArrayList that I can access later.
Here is my Item class:
import java.util.ArrayList;
import java.util.*;
public class Item
{
private String name;
private int quantity;
private ArrayList<Item> allItems = new ArrayList<Item>(); //the ArrayList I'm trying to fill with every Item object
/**
* Constructs an item of a given name and quantity
* #param name Item name
* #param quantity How much of an item the player has
*/
public Item(String name, int quantity)
{
this.name = name;
this.quantity = quantity;
}
/**
* #return Item name
*/
public String getItemName()
{
return name;
}
/**
* #return Quantity of the item
*/
public int getQuantity()
{
return quantity;
}
/**
* #return A list of items that have a quantity > 0
*/
public ArrayList<Item> getInventory()
{
ArrayList<Item> inventory = new ArrayList<Item>();
for(Item i : allItems)
{
if(i.getQuantity() > 0)
inventory.add(i);
}
return inventory;
}
}
How can I add an Item object to allItems every time one is constructed?
First, the arraylis must be static so it is shared between all the instances.
Otherwise, you would have a different variable per instance.
More info on instance/class members here.
private String name;
private int quantity;
private static ArrayList<Item> allItems = new ArrayList<Item>();
Then, you can add the created instance in the constructor, refering to it as 'this'.
About the 'this' keyword.
public Item(String name, int quantity)
{
this.name = name;
this.quantity = quantity;
allItems.add(this);
}
You certainly want one list for all items, and not every item to carry around and maintain its own copy list of all items. When that's your intention, you should define the list as static:
private static ArrayList<Item> allItems = new ArrayList<Item>()
A static variable is shared by all instances of the class.
In the constructor of Item, just add this to the list of all items.
allItems.add(this);
You need a static List and then you can use the class constructor to add this object into the list.
import java.util.ArrayList;
import java.util.*;
public class Item
{
private String name;
private int quantity;
private static ArrayList<Item> allItems = new ArrayList<Item>(); //the ArrayList I'm trying to fill with every Item object
/**
* Constructs an item of a given name and quantity
* #param name Item name
* #param quantity How much of an item the player has
*/
public Item(String name, int quantity)
{
this.name = name;
this.quantity = quantity;
allItems.add(this);
}
/**
* #return Item name
*/
public String getItemName()
{
return name;
}
/**
* #return Quantity of the item
*/
public int getQuantity()
{
return quantity;
}
/**
* #return A list of items that have a quantity > 0
*/
public static ArrayList<Item> getInventory()
{
ArrayList<Item> inventory = new ArrayList<Item>();
for(Item i : allItems)
{
if(i.getQuantity() > 0)
inventory.add(i);
}
return inventory;
}
}
One possible solution would be to declare the items list as static like this:
public static List<Item> allItems = new ArrayList<Item>();
afterwards you could access it using the following snippet:
Item.allItems // example would be System.out.println(Item.allItems)
Additionally within your constructor you will need the following code:
public Item(String name, int quantity) {
this.name = name;
this.quantity = quantity;
this.allItems.add(this);
}
BUT use this approach with caution, since it will add to list every single item created, what could lead to a possible memory leak.
Related
It's a code about a 'shopping cart' that can hold items of a class called 'item'. I had to complete the class 'item' and write another class 'discount' that can reduces the price of an item.
import java.util.ArrayList;
public class Shoppingcart extends Item {
// all shopping carts:
private ArrayList<Shoppingcart> allshoppingcart = new ArrayList<Shoppingcart>();
//Items in the shopping cart:
private ArrayList<Item> content = new ArrayList<Item>();
// Counter for shopping carts
private static int number;
/**
* Constructor
*/
public Shoppingcart() {
allshoppingcart .add(this);
this.number = number ;
this.number++;
}
/**
* load something in Shoppingcart
*/
public void load(Item i) {
this.content.add(i);
}
/**
* Sum of all items loaded in the shoppingcart
*
* #return sum of the content in the shopping cart
*/
public double sumShoppingCart() {
double sum = 0.0;
for (Item i : content) {
sum = sum + item.getPrice();
}
return sum;
}
}
The class 'item' so I can store two different types in the arraylist.
public class Item {
// normal price of item
protected double price;
// Name of product
protected String name;
/**
* setter for price and name
*/
public void setPB(String name, double price) {
this.name = name;
this.price = price;
}
/**
* getter for price
*/
public double getPrice() {
return this.price;
}
/**
* getter for the name
*/
public String getName() {
return this.name;
}
}
The class 'discount' to reduce an item for an example like a sale (special-offer).
public class Discount extends Item
{
// instance variables - replace the example below with your own
public Discount()
{
// initialise instance variables
}
public void makeSale(int percent){
percent =(100-percent)/100;
price = w.getPrice()*percent;
}
}
A test class
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<Item> content = new ArrayList<>();
Item item = new Item();
Item item1 = new Item();
Item item2 = new Item();
item.setPB("Steak", 100.00);
item1.setPB("Water", 200.00);
item2.setPB("Groceries", 300.00);
content.add(item);
content.add(item1);
content.add(item2);
System.out.println("The item has the value : " + item.getPrice() + " and the name: " + item.getName());
System.out.println("There are : " + content.size() + " Item(s) in the shopping cart.");
}
}
How do I access an item and reduce it for a sale?
Thank you
This is a typical OOP exercise. You want to access two different types in a single collection. To do so they both need to have the same interface or parent.
If you use an Abstract base class you can use the following example.
First lets make an abstract Item class:
abstract class Item {
protected double price;
protected String name;
public Item(double price, String name) {
this.price = price;
this.name = name;
}
public double getPrice() {
return this.price;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setPrice(double price) {
this.price = price;
}
abstract void discount(double amount);
}
and two classes that extend from this base class:
class Food extends Item {
public Food(double price, String name) {
super(price, name);
}
#Override
void discount(double amount) {
this.price -= amount;
}
}
class Bevarage extends Item {
public Bevarage(double price, String name) {
super(price, name);
}
#Override
void discount(double amount) {
this.price -= amount;
}
}
Now lets make a class discount that has a List items that can discount both items.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Discount {
public void printAllContent(List<Item> items) {
items.forEach(item -> System.out.printf("name = %s, price = %.00f \n", item.getName(), item.getPrice()));
}
public static void main(String[] args) {
Discount card = new Discount();
List<Item> items = Arrays.asList(
new Food(3.0, "burgers"), new Food(9.0, "tomato"), new Food(8.0, "fries"),
new Bevarage(9.0, "cola"), new Bevarage(12.0, "water"), new Food(2.0, "beer")
);
card.printAllContent(items);
for (Item item : items) {
item.discount(1.0);
}
card.printAllContent(items);
// if you want to do different discounts for different items
for(Item item: items) {
if (item instanceof Bevarage) {
item.discount(2.0);
} else {
item.discount(1.0);
}
}
card.printAllContent(items);
}
}
java.util.List has these functions get(index) and set(index, object), which you could use:
//1. get your item
int index = 0;
Item item=content.get(index);
//2. create your discount
Discount discount=new Discount();
// Fill/process your discount object with the appropriate data
//3. replace the item with the discount in the list
content.set(index,discount);
I have an abstract class called items and would like to create two classes called Appliance and SmallHwItem that extend items class. In my items abstract class I have variables that will be constant for both classes that extend it, but would like to add different variables to the items constructor within the appliance and smallhwitem classes. For example: Id like to include string variables "Type", "Brand", and "Category" in the appliance class. Sorry I am new to abstract classes and would appreciate any feedback. Here are my two classes below.
Items.java:
package hardwarestore;
import java.io.Serializable;
/**
* This class is a very simple representation of a hardware item. There are only getter
* methods and no setter methods and as a result an item cannot be mutated once
* initialized. An item object can also call the two override methods
* <CODE>toString()</CODE> and <CODE>equals()</CODE>
*
*/
public abstract class Item implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private final String idNumber;
private final String name;
private int quantity;
private final float price;
public Item(String idNumber, String name, String category, int quantity, float price) {
this.idNumber = idNumber;
this.name = name;
this.quantity = quantity;
this.price = price;
}
/**
* This method returns the item's tracking number.
*
* #return a <b><CODE>String</CODE></b> that is the ID number of the item.
*/
public String getIdNumber() {
return idNumber;
}
/**
* This method returns the item's name.
*
* #return a <b><CODE>String</CODE></b> that is the item's name.
*/
public String getName() {
return name;
}
/**
* This method returns the item's quantity.
*
* #return an <b><CODE>int</CODE></b> that is the item's weight
*/
public int getQuantity() {
return quantity;
}
/**
* This method set the item's quantity.
*
* #param quantity a <b><CODE>int</CODE></b> that represents the quantity
*/
public void setQuantity(int quantity) {
this.quantity= quantity;
}
/**
* This method returns the item's price.
*
* #return a <b><CODE>float</CODE></b> that is the item's price
*/
public float getPrice() {
return price;
}
/**
* This abstract method returns the item's fields as a string representation.
*
* #return a <b><CODE>String</CODE></b> that lists the fields of the item
* object delineated by a space and in the same order as the constructor
*/
public abstract String getFormattedInfo();
/**
* This method provides a way to compare two item objects.
*
* #param c a <b><CODE>Item</CODE></b> object that is used to compare to
* <b><CODE>this</CODE></b> item. Two orders are equal if their ID is the
* same.
* #return the <CODE>boolean</CODE> value of the comparison.
*/
public boolean equals(Item c) {
return c.getIdNumber().equals(this.idNumber);
}
}
Appliance.java:
package hardwarestore;
public class Appliance extends Item{
private static final long serialVersionUID = 1L;
private final String brand;
private final String type;
private final String category;
public Appliance(String idNumber, String name, String brand, String type, String category, int quantity, float price) {
super(idNumber, name, brand, quantity, price);
}
public String getFormattedInfo() {
return null;
}
}
Just set the fields in your concrete class Appliance with this
public Appliance(String idNumber, String name, String brand, String type, String category, int quantity, float price) {
super(idNumber, name, category, quantity, price);
this.brand = brand;
this.type = type;
this.category = category;
}
By the way, you're not using category in the abstract constructor.
I am trying to finish my home assignment for programming class, unfortunately getting stuck through half of it ,due to my stupidity. ArrayList that I have created overwrites 0 index constantly.
Here are my classes for creating invoices:
import java.util.ArrayList;
public class Order
{
private String customerName;
private ArrayList<LineItem> items = new ArrayList<LineItem>();
public Order(String customerName)
{
this.customerName = customerName;
}
public String getCustomerName()
{
return customerName;
}
public ArrayList<LineItem> getItems()
{
return this.items;
}
public double getOrderTotal()
{
double totalOrder = items.get(0).getTotalPrice();
return totalOrder;
}
public void addItem(String description,double unitPrice, int quantity)
{
LineItem object = new LineItem(description,unitPrice,quantity);
items.add(object);
}
public String toString()
{
String.format("%n%-20s%-15s%-15f%-15f",items.get(0).getDescription(),
items.get(0).getQuantity(),items.get(0).getUnitPrice(),getOrderTotal());
return p;`
}
}
public class LineItem
{
private String description;
private double unitPrice;
private int quantity;
public LineItem(String description,double unitPrice, int quantity)
{
this.description = description;
this.unitPrice = unitPrice;
this.quantity = quantity;
}
public String getDescription()
{
return this.description;
}
public double getUnitPrice()
{
return this.unitPrice;
}
public int getQuantity()
{
return this.quantity;
}
public double getTotalPrice()
{
return this.unitPrice * this.quantity;
}
public String toString()
{
return String(this.description,this.unitPrice,this.quantity)
}
}
AND a part of ... while LOOP for main class
do
{
customerName = AssignmentHelper.getRequiredStringInput("Please enterthe customer's name: ","A customer name must be entered!");
newOrder = new Order(customerName);
newOrder.addItem(description,unitPrice,quantity);
} while(Character.toString(userAnswer).equalsIgnoreCase ("Y"));
Your loop creates a new Order object in each iteration :
newOrder = new Order(customerName);
Each Order object has a new empty ArrayList, which is why it seems the first index is always overwritten.
If you want a single ArrayList to hold all the items, you should create a single Order object prior to the do-while loop.
newOrder = new Order(customerName);
do {
...
newOrder.addItem(description,unitPrice,quantity);
} while(Character.toString(userAnswer).equalsIgnoreCase ("Y"));
In the loop, a new order object is created which has two fields (customer name and an Arraylist of line items). Initially the ArrayList will be empty.The call to addItem object creates a new Lineitem object and add its to the ArrayList items. Therefore the lineItem object will always be added to index zero.
Create a new object only when a new customer is added.You can have a HashMap where key is the customer name. If the key already exists add to the same object else create a new order object and it to the Map.
I have a school project entitled "Amusement Park Programming Project"
It requires four classes to be created:
Ticket - Models admission tickets
Merchandise - Models merchandise available in gift shop
AmusementPark - Tracks ticket and merchandise inventory / sales
WaldenAmusementPark - Tester program
AmusementPark Class is where I need help - I understand what needs to be happening per the instructions but I am unclear on how to access getter / setter methods and ArrayLists that are defined in Ticket and Merchandise to make things happen - I am reading the guidance, watching videos but unable to make it work?:
I've pasted my code (such as it is) below - any guidance is appreciated Not looking for the actual code to be written - just to clear up my confusion. Thanks in advance.
----------------TICKET CLASS----------------------------------
import java.util.*;
public class Ticket {
//Ticket Class models admission tickets
//Instance Variables called for in the instructions
private long number;
private String category;
private String holder;
private Date date;
private double price;
private boolean purchased;
// Constructor Ticket -- The instructions did not call for instance field "number" as a parameter and left "purchased" out of the UML???
public Ticket (long number, String category, String holder, Date date, double price, boolean purchased){
this.number = number; //Stores unique ticket ID Number
this.category = category; //Stores adult, child, or senior
this.holder = holder; //Stores name of purchaser
this.date = date; //Stores admission date for the ticket
this.price = price; //Stores price of the ticket
this.purchased = purchased; //Stores true if purchased, false if reserved
} // End Brace Constructor Ticket
// MUTATOR METHODS..............................................
// setPrice Mutator Method
public void setPrice(double price){
this.price = price;
} // End Brace setPrice
//changePurchaseStatus Mutator Method
public void setchangePurchaseStatus(boolean newStatus){
this.purchased = newStatus;
} // End Brace changePurchasedStatus
// ACCESSOR METHODS.............................................
//getnumber Accessor Method
public long getnumber(){
return number;
}
//getcategory Accessor Method
public String getcategory(){
return category;
}
//getholder Accessor Method
public String getholder(){
return holder;
}
//getdate Accessor Method
public Date getdate(){
return date;
}
//getprice Accessor Method
public double getprice(){
return price;
}
//getpurchased Accessor Method
public boolean getpurchased(){
return purchased;
}
} // End Brace Ticket Class
--------------------------MERCHANDISE CLASS------------------------------
public class Merchandise {
//Instance Variables called for in the instructions
private long ID; //ID of specific merchandise item
private String category; //Stores type of item (T-Shirt, Sweatshirt, Stuffed Animal) - if invalid display "Unknown"
private String description; //Stores description of item
private double price; //Stores price of item
private boolean instock; //True = in stock False = on order
// Constructor Merchandise
public Merchandise(long ID, String category, String description, double price, boolean instock){
this.ID = ID;
this.category = category;
this.description = description;
this.price = price;
this.instock = instock;
} // End Brace Constructor Merchandise
// MUTATOR METHODS..............................................
public void setPrice(double price){
this.price = price;
}
public void setInstock(boolean newStatus){
this.instock = newStatus;
}
// ACCESSOR METHODS.............................................
public long getID(){
return ID;
}
public String getcategory(){
return category;
}
public String getdescription(){
return description;
}
public double getprice(){
return price;
}
public boolean getinstock(){
return instock;
}
// toString Method.............................................
#Override
public String toString(){
return("Merchandise ID:" + "\t" + this.ID + "\n" + "Merchandise Category:" + "\t" + this.category + "\n"
+ "\t" + "Merchandise Description:" + "\t" + this.description + "$" + this.price + "\t"
+ "In-Stock Status" + "\t" + this.instock);
}
} //End Brace Merchandise Class
------------------------AMUSEMENT PARK CLASS---------Where I Need Help!!--------
import java.util.ArrayList;
import java.util.Date;
public class AmusementPark {
//Instance Variables called for in the instructions
private String name = "Walden Gift Shop"; // Assigned a value that I think is needed to support "getName" Accessor Method
private Date date; // Not called for in the instruction but I believe it is needed
//ArrayLists
public static ArrayList<Ticket> tickets = new ArrayList<Ticket>(); //Stores ticket objects
public static ArrayList<Merchandise> merchandise = new ArrayList<Merchandise>(); //Stores Merchandise objects
// Stores ArrayList of type Date called "ticketDate" that has all dates for which tickets are still available
// This ArrayList was not clearly called for in the instructions but is required to return dates for which tickets are still available -
// if no tickets are available return empty list
/** public ArrayList<Date> ticketDate(){
ArrayList<Date> ticketDate = new ArrayList<Date>();
Date.(2014, 03, 01);
} */
// Constructor AmusementPark
public AmusementPark(String name){ //How should I be referencing / using the ArrayLists tickets & merchandise in the constructor??????
this.name = name;
}
// ACCESSOR METHODS.............................................
public String getName(){ // Returns the name of the amusement park shop
return name;
}
//--------------------- Have 3 getters to return various Ticket data - Need to fix the stubs for them shown below----------------------
// Need to fix this getTicketDates getter
/** public getTicketDates(){ //Returns an ArrayList<Date> of all dates tickets are still available
return
} */
// Need to fix this getTickets getter
/** public Date getTickets(){ // Returns an integer indicating number of tickets available for specified date
return date;
} */
// Need to fix this getTicket getter
/** public long getTicket (long id){ //Returns Ticket number / ID that matches the specified ticket
Ticket myTicketID = new Ticket();
id.getnumber();
}*/
//---------------------------END the 3 "getMerchandise" getters----------------------------------------------------------------------
//--------------------- Have 3 "getMerchandise" getters to define - Need to fix the stubs for them shown below----------------------
// Need to fix this getMerchandise getter
/** public getMerchandise(){ //Returns an Arraylist<Merchandise> of all inventory - if no match return empty list
return ;
} */
//Need to fix this getMerchandise getter
/** public getMerchandise (String category){ //Returns a list of Merchandise objects whose category matches the specified (e.g., T-Shirts), no match return empty list
return
}*/
//Need to fix this getMerchandise getter
/** public getMerchandise (long id){ //Returns the merchandise item that matches the specified id number, if not match return null
return
}*/
//---------------------------END the 3 "getMerchandise" getters----------------------------------------------------------------------
//Need to fix this addTicket Mutator method
/** public addTicket (Ticket) { // Adds a new Ticket to the inventory of AmusementPark Class
} */
//Need to fix this buyMerchandise Mutator method
/** public buyMerchandise (String id){ //Removes a Merchandise object from teh list of merchandise of the AmusementPark Class, if no match throw exception
} */
//Need to fix this buyTicket Mutator method
/** public buyMerchandise (String id){ //Removes a Ticket object from the list of ticket items of the AmusementPark Class - If not match throw exception
} */
} // End Brace AmusementPark Class
You need to instantiate a Ticket object where you need it.
Ticket yourTickecObject = new Ticket(constructor parameters);
And then just call the getter to get data
int price = yourTicketObject.getPrice();
And setter to set data
yourTicketObject.setPrice(someValue);
It's the same for ArrayList, Declaration in ticket:
ArrayList<someTipe> yourArrayListName = new ArrayList<someTipe>();
getter:
full Array list:
public ArrayList getYourArrayListName(){
return this.yourArrayListName;
}
specific item:
public yourArrayListType getItem(index){
return this.yourArrayListName.get(index)
}
setter:
If you want to add one item:
public void addObjectToYourArrayListName(SomeValidType argument){
this.yourArrayListName.add(argument);
}
If you want to set the ArrayList:
public void setYourArrayListName(ArrayList<someValidType> argument){
this.yourArrayListName = argument;
}
To access you Array List:
setter:
add an item:
yourTicketObject.addObjectToYourArrayListName(SomeValidType argument)
add a full ArrayList:
yourTicketObject.setYourArrayListName(ArrayList<someValidType>)
getter:
get full array list:
Arraylist<someType> someName = yourTicketObject.getYourArrayListName()
get specific index:
YourArrayListType variableName = yourTicketObject.getItem(index)
All this code is abstract you can use it every where adapted, pay attention to the types of variables.
Hope this helped
i'm new to java and I am having problems adding my array objects to my list. I have already checked the topics in this forum but can't find something similar to my problem.
I have already made a class called Item that will save information about an item to be sold, and it has 4 instance variables id, desc, cost, quantity. And then I have a Sales class which has my main method. Basically what I want to do is build an array of objects from my Item class and hard code my data(which I have already created, i'm not sure if I did it right though).
I have created an ArrayList and what I want to do now is add the 5 objects from the array that I created into the list.
This is my Item class
public class Item {
private String itemID;
private String desc;
private double cost;
private int quantity;
public Item() {
itemID="";
desc="";
cost=0;
quantity=0;
}
public Item(String id, String d, double c, int q) {
itemID = id;
desc = d;
cost = c;
quantity = q;
}
/**
* #return the itemID
*/
public String getItemID() {
return itemID;
}
/**
* #param itemID the itemID to set
*/
public void setItemID(String itemID) {
this.itemID = itemID;
}
/**
* #return the desc
*/
public String getDesc() {
return desc;
}
/**
* #param desc the desc to set
*/
public void setDesc(String desc) {
this.desc = desc;
}
/**
* #return the cost
*/
public double getCost() {
return cost;
}
/**
* #param cost the cost to set
*/
public void setCost(double cost) {
this.cost = cost;
}
/**
* #return the quantity
*/
public int getQuantity() {
return quantity;
}
/**
* #param quantity the quantity to set
*/
public void setQuantity(int quantity) {
this.quantity = quantity;
}
/* (non-Javadoc)
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
return "Item [itemID=" + itemID + ", desc=" + desc + ", cost=" + cost
+ ", quantity=" + quantity + "]";
}
}
And my Sales class:
import java.util.*;
public class Sales {
/**
* #param args
*/
public static void main(String[] args) {
int i;
Item[] items = new Item[5];
for(i = 0; i < items.length; i++)
{
items[i]= new Item(); // create array
}
//hard-coded values of id, desc, cost, qty
items[0].setItemID("PN250");
items[1].setItemID("ER100");
items[2].setItemID("PP150");
items[3].setItemID("MK200");
items[4].setItemID("PN300");
items[0].setDesc("Pen");
items[1].setDesc("Eraser");
items[2].setDesc("Paper");
items[3].setDesc("Marker");
items[4].setDesc("Pen");
items[0].setCost(1.50);
items[1].setCost(1.25);
items[2].setCost(3.75);
items[3].setCost(2.50);
items[4].setCost(2.25);
items[0].setQuantity(0);
items[1].setQuantity(175);
items[2].setQuantity(310);
items[3].setQuantity(75);
items[4].setQuantity(450);
double total = 0;
for(Item d : items)
{
System.out.print(d.getItemID());
System.out.print("\t" + d.getDesc());
System.out.print("\t" + d.getCost());
System.out.println("\t" + d.getQuantity());
}
List<Item> obj;
obj = new ArrayList<Item>();
}
}
You could add the array into your list with the following:
obj.addAll(Arrays.asList(items));
You can use:
for (i = 0; i < items.length; i++)
{
obj.add(items[i]);
}
but why not add the items as soon as they are created & populated?
instead of creating an array at the beginning of your function, create an arrayList and add objects to it using the put method.
Also, you should think of making your objects immutables and pass their attributes to their constructor instead of calling the setter for each attribute