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
Related
I was creating a Java program for my OOP class. The program is supposed to be the start of a store interface and we are going to build off it during the rest of the semester. Whenever I was to add a new product and try to access how much of it is in stock my program says the "Id DNE -1" which is only supposed to print when an id is called and it doesn't exist. I'm not too sure why it's not recognizing the product I just put in. Below are all my classes that are used. I think the error has to be somewhere in my inventory class but I'm not too sure. Any tips or tricks for OOP would greatly be appreciated as well. Cheers
public class main
{
public static void main(String[] args)
{
StoreManager r3 = new StoreManager();
Inventory r4 = new Inventory();
r4.addNewProduct(1,"apple",1.50,50);
System.out.println(r3.qCheck(1));
}
}
public class StoreManager
{
private Inventory store1 = new Inventory();
private Product store2 = new Product();
static Inventory r4 = new Inventory();
public StoreManager(){}
public int qCheck(int id)
{
if (store1.getStock(id) < 0)
{
System.out.println("Id DNE");
return -1;
} else
{
return store1.getStock(id);
}
}
public double dqcheck(int id, int desiredQuantity) {
if (store1.getStock(id) >= desiredQuantity) {
store1.removeStock(id, desiredQuantity);
double cost = store2.getPrice() * desiredQuantity;
return cost;
}
else {
System.out.println("id DNE");
}
return -1;
}
}
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class Inventory
{
//Var Declarations
private int quantity;
// FIXME: 2021-02-07 idk if im usin type right
private Product type;
//Hashmap for the data structure in this class using the Product is gonna be a key
// the value is the Integer for the quantity
private Map<Product,Integer> invt = new HashMap<>();
//blank constructor
public Inventory()
{
}
// FIXME: 2021-02-05 Getter and setter methods not really in use
public int getQuantity(){return quantity;}
public Product getType(){return type;}
/*
Used to initialize a new product and its stock into our Hashmap
the Quantity is the Value of our hashmap while we are using the
Product as a whole to be the key
no return type
*/
public void addNewProduct(int id,String name, double price, int quantity)
{
Product product = new Product(name, id, price);
invt.put(product,quantity);
}
/*
Used to get the get for a given id
compares the Id to one of the ids in the Key values to find the product
returns an int for the amount in stock or a -1 as an error if the id doesn't exist
*/
public int getStock(int id)
{
Set<Product> set = invt.keySet(); // Conversion of keys into sets
Iterator<Product> it = set.iterator(); // the only way i could get the code to interate throughout the keys
while (it.hasNext())//Only way i could go through the code
{
type = it.next();// FIXME: 2021-02-07 Idk if type is being used right here but i needed a buffer variable for it to work
Product a = it.next();
if (a.getId() == id)
{
return invt.get(type);//type is an object of Product here so we can use it as a key
}
}
return -1;//representation of error ID Dne
}
/*
Used to add a given Stock for a given Id
void doesnt return anything
assuming inpputed id exists if Dne doesnt do anythin or return an error
*/
public void addStock(int id, int amountToAdd)
{
//Possibly make this hashmap id check into another private method and call
Set<Product> set = invt.keySet();
Iterator<Product> it = set.iterator();
while (it.hasNext())
{
type = it.next();
if (type.getId() == id)
{
invt.put(type, invt.get(type)+amountToAdd);
return;//exit the function after the addtion is done
}
}
}
/*
Used to remove a given amount of product from stock in reference to a given Id
void doesnt return anythin
assuming id exits otherwise it does nothin
*/
public void removeStock(int id, int amountToRemove)
{
Set<Product> set = invt.keySet();
Iterator<Product> it = set.iterator();
while (it.hasNext())
{
type = it.next();
if (type.getId() == id && invt.get(type) - amountToRemove >= 0)//checks if the id exits and if there whould be enough stock to remove
{
invt.put(type, invt.get(type)-amountToRemove);
return;
}
}
}
/*
Prints all product information in reference to the id
*/
public void getInfo(int id)
{
Set<Product> set = invt.keySet();
Iterator<Product> it = set.iterator();
while (it.hasNext())
{
type = it.next();
if (type.getId() == id)
{
System.out.println("Name: "+type.getName());
System.out.println("Id: "+type.getId());
System.out.println("Price: "+type.getPrice());
System.out.println("Quantity: "+ invt.get(type)); // FIXME: 2021-02-07 Idk if Quanitity and Id are needed here
}
}
}
}
public class Product
{
private String name;
private int Id;
private double price;
public Product(String Name, int Id,double Price)
{
this.name = Name;
this.Id = Id;
this.price = Price;
}
public Product()
{
}
//Getter Methods
public String getName() {return name;}
public int getId() {return Id;}
public double getPrice() {return price;}
}
public class main
{
public static void main(String[] args)
{
StoreManager r3 = new StoreManager();
r3.store1.addNewProduct(1,"apple",1.50,50);
System.out.println(r3.qCheck(1));
}
}
Use the Inventory object that belongs to StoreManager, that's the only one it can access.
I am writing a simple inventory system for practice and I have an item class that holds these values:
private String name;
private int quantity;
private Integer ID;
private Double pricePerUnit;
private Double totalPrice;
I am writing the constructors for this class and I want everything except the name and quantity to be optional, as in the user can opt whether or not to input any data for those fields. Currently I have two constructors that look like this:
public Item(String name, int quantity)
{
this.name=name;
this.quantity=quantity;
}
public Item(String name, int quantity, Integer ID, Double pricePerUnit, Double totalPrice)
{
this(name, quantity);
this.ID=ID;
this.pricePerUnit=pricePerUnit;
this.totalPrice=totalPrice;
}
Is there any way I can make some of the arguments in the second constructor optional, or non-mandatory?
Thanks!
Naturally, in such cases I'd would think of two possibilities to get what you need, Constructor Overloading and Builder Pattern
Although when you have the same data formats, You can't naturally depend on the former. In such cases (as OP's Question) the best alternative is to go for a builder design pattern.
You can build an instance of Item.class as the following
public class Item {
\\... other public functions.. etc
static class ItemBuilder{
private Item item;
public ItemBuilder withNameAndQuantity(String name, int quantity){
item = new Item(); //default constructor or as per your usecase a private constructor
item.setName(name);
item.setQuantity(quantity);
return this;
}
public ItemBuilder withPricePerUnit(Double pricePerUnit){
if(item!=null){
item.setPriceUnit(pricePerUnit);
}
return this;
}
public ItemBuilder withTotalPrice(Double totalPrice){
if(item!=null){
item.setTotalPrice(totalPrice);
}
return this;
}
public Item build(){
if(item!=null){
return item;
}else{
throw new IllegalStateException("item is null, no name or id set");
}
}
}
}
Finally, you could build a new Item by doing the following :
Item item = new Item.ItemBuilder(). withNameAndQuantity("apple",10). withTotalPrice(100).build();
Ideally you would decompose the class into coherent pieces, in much the same way as you might normalise a database schema.
There is the Builder Pattern.
You code could be written better by making the constructor will all the attributes the "canonical constructor* and forward to that. This will also make it easier to switch over to records when they become available.
public Item(String name, int quantity) {
this(name, quantity, null, null, null);
}
public Item(String name, int quantity, Integer id, Double pricePerUnit, Double totalPrice) {
this.name = name;
this.quantity = quantity;
this.ID = ID;
this.pricePerUnit = pricePerUnit;
this.totalPrice = totalPrice; // Shouldn't this be calculated?
}
(Not that nulls are ideal.)
One way is to create more constructors and another is to loose the immutability and introduce setter methods.
Hence, you can use Builder Pattern as Builder Pattern will help you to consume additional attributes while retaining the immutability of Item class.
Below is the coded solution. This uses a additional class ItemBuilder which helps us in building desired Item object with all mandatory attributes and combination of optional attributes, without loosing the immutability.
public class Item {
//All final attributes
private String name; // required
private int quantity; // required
private Integer ID; // optional
private Double pricePerUnit; // optional
private Double totalPrice; // optional
private Item(ItemBuilder builder) {
this.name = builder.name;
this.quantity = builder.quantity;
this.ID = builder.ID;
this.pricePerUnit = builder.pricePerUnit;
this.totalPrice = builder.totalPrice;
}
//All getter, and NO setter to provide immutability
public String getName() {
return name;
}
public int getQuantity() {
return quantity;
}
public Integer getID() {
return ID;
}
public Double getPricePerUnit() {
return pricePerUnit;
}
public Double getTotalPrice() {
return totalPrice;
}
#Override
public String toString() {
return "User: "+this.name+", "+this.quantity+", "+this.ID+", "+this.pricePerUnit+", "+this.totalPrice;
}
public static class ItemBuilder
{
private String name; // required
private int quantity; // required
private Integer ID; // optional
private Double pricePerUnit; // optional
private Double totalPrice; // optional
public ItemBuilder(String name, int quantity) {
this.name = name;
this.quantity = quantity;
}
public ItemBuilder ID(Integer ID) {
this.ID = ID;
return this;
}
public ItemBuilder pricePerUnit(Double pricePerUnit) {
this.pricePerUnit = pricePerUnit;
return this;
}
public ItemBuilder totalPrice(Double totalPrice) {
this.totalPrice = totalPrice;
return this;
}
//Return the finally constructed Item object
public Item build() {
Item item = new Item(this);
validateUserObject(item);
return item;
}
private void validateUserObject(Item item) {
//Do some basic validations to check
//if item object does not break any assumption of system
}
}
}
OR
You can also make use of JsonProperties.
#JsonIgnoreProperties(ignoreUnknown = true)
public record Item(
String name,
Integer quantity,
#JsonInclude(JsonInclude.Include.NON_NULL) Integer ID,
#JsonInclude(JsonInclude.Include.NON_NULL) Double pricePerUnit,
#JsonInclude(JsonInclude.Include.NON_NULL) Double totalPrice) {}
I hope this gives you clarity on how to resolve your problem.
I have a String in this format (including curly brackets):
{id=123, vehicle_name=Tesla Model X, price=80000.00, ... }
What is the appropriate Java object to represent this String, and how can I convert it to that object?
I would like to be able to query the object to retrieve its values easily, eg. obj.get("vehicle_name"). I've tried converting it to JSON using JSONObject however this expects colons as the delimiters between keys and values, rather than the equals sign.
String itself is a java object.
Parsing String and filling up a java object is not clean.
You can create a java pojo Vehicle with attributeS like id,
vehicle_name etc. Assuming your String will always follow a same
pattern.
Parse the String, and fill this Vehicle pojo.
Below is just a simple example, on how to do it :-
public class Test {
public static void main(String[] args){
String text="{id=123, vehicle_name=Tesla Model X, price=80000.00}";
text=text.replaceAll("[{}]", "");
String[] commaDelimitArray=text.split(",");
Vehicle vehicle=new Vehicle();
for(int i=0;i<commaDelimitArray.length;i++){
String[] keyValuePair=commaDelimitArray[i].split("=");
String key=keyValuePair[0].trim();
String value=keyValuePair[1].trim();
if("id".equals(key)){
vehicle.setId(value);
}
else if("vehicle_name".equals(key)){
vehicle.setVehicleName(value);
}
else if("price".equals(key)){
vehicle.setPrice(value);
}
}
System.out.println(vehicle.getId()+" |"+vehicle.getVehicleName());
}
static class Vehicle{
private String id;
private String vehicleName;
private String price;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getVehicleName() {
return vehicleName;
}
public void setVehicleName(String vehicleName) {
this.vehicleName = vehicleName;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
}
This appears to be an assignment in creating Object classes. If so, you want to create something like this:
public class Car {
int id;
String name;
double price;
//include any other necessary variables
public Car(int id, String name, double price) {
this.id = id;
this.name = name;
this.price = price;
//include any other variables in constructor header and body
}
public void setID(int newID) {
id = newID;
}
public int getID() {
return id;
}
//add getters and setters for other variables in this same manner
}
Note that you could alternatively create a constructor that takes no parameters and initializes variables to default values, then set the values individually using the setter methods.
In your main class, what you want to do is extract the appropriate substrings from your String to pass to the constructor (or setters). There are various ways of doing this (you can read about some ways here); I would personally recommend using regular expressions and a Matcher.
If I had such a string which needed to be converted to an object I would create a class with a static method which returns a Vehicle object. Then you can do whatever you want with that object. A few getters and setters and you should be good to go.
I have come up with some code which should work as you expect if I have understood your question :)
There is quite a few comments so this should help you understand the code logic.
The Vehicle Class is where all parsing happens in the static method named createVehicle(String keyValueString).
The main class:
import java.util.ArrayList;
import java.util.List;
public class main {
public static void main(String[] args) {
String vehicleString = "{id=123, vehicle_name=Tesla Model X, price=80000.00}";
List<Vehicle> vehicles = new ArrayList<Vehicle>();
Vehicle vehicle;
// call the static method passing the string for one vehicle
vehicle = Vehicle.createVehicle(vehicleString);
// if the id is -1, then the default constructor fired since
// there was an error when parsing the code.
if(vehicle.getId() == -1 ) {
System.out.println("Check your data buddy.");
} else {
vehicles.add(vehicle);
}
for(Vehicle v : vehicles){
System.out.println("Vehicle id: " + v.getId());
System.out.println("Vehicle name: " + v.getVehicle_name());
System.out.println("Vehicle price: " + v.getPrice());
System.out.println();
}
}
}
The Vehicle Class:
import java.math.BigDecimal;
public class Vehicle {
// declare your attributes mapped to your string
private int id;
private String vehicle_name;
private BigDecimal price;
// Start Constructor
// Default Constructor
public Vehicle() {
this.setId(-1);
this.setVehicle_name("Empty");
this.setPrice(new BigDecimal(0.00));
}
public Vehicle(int id, String vehicle_name, BigDecimal price) {
this.setId(id);
this.setVehicle_name(vehicle_name);
this.setPrice(price);
}
// End Constructor
// Start Getters and Setters
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getVehicle_name() {
return vehicle_name;
}
public void setVehicle_name(String vehicle_name) {
this.vehicle_name = vehicle_name;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
// End Getters and Setters.
// Start Methods and Functions
// Given a string returns a string array split by a "," and with
// "{}" removed.
private static String[] splitString(String keyValueString) {
String[] split;
// Clean string from unwanted values
keyValueString = keyValueString.replaceAll("[{}]", "");
split = keyValueString.split(",");
return split;
}
// Add a vehicle given a formatted string with key value pairs
public static Vehicle createVehicle(String keyValueString) {
int id = 0;
String vehicle_name = "";
BigDecimal price = null;
String[] split;
Vehicle vehicle;
split = splitString(keyValueString);
// Loop through each keyValue array
for(String keyValueJoined : split){
// split the keyValue again using the "="
String[] keyValue = keyValueJoined.split("=");
// remove white space and add to a String variable
String key = keyValue[0].trim();
String value = keyValue[1].trim();
// check which attribute you currently have and add
// to the appropriate variable
switch(key){
case "id":
id = Integer.parseInt(value);
break;
case "vehicle_name":
vehicle_name = value;
break;
case "price":
try {
price = new BigDecimal(Double.parseDouble(value));
} catch (NumberFormatException e) {
e.printStackTrace();
}
break;
default:
System.out.println("Attribute not available");
return null;
}
}
// if any of the values have not been changed then either the
// data is incomplete or inconsistent so return the default constructor.
// Can be removed or changed if you expected incomplete data. It all
// depends how you would like to handle this.
if(id == 0 || vehicle_name.equals("") || price == null){
vehicle = new Vehicle();
} else {
//System.out.println(id);
vehicle = new Vehicle(id, vehicle_name, price);
}
return vehicle;
}
// End Methods and Functions
}
The program, given the string provided, returns the following when accessing the newly created object attributes using the getters:
Vehicle id: 123 Vehicle name: Tesla Model X Vehicle
price: 80000
Hope this helps.
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'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.