ArrayList of Objects from a different class - java

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());
}
}
}

Related

DynamicJasper - How to add a subreport as columns?

Overview
I have a Java class which has an ArrayList that must be printed to
the jasperReport as a subreport.
I'm using DynamicJasper library.
The example on this question has been modified so it can be reproduced. However the data is different on the real case.
Problem
The current code Ive come with, prints the subreport in another line. Its ugly. I wanted the subreport to just be a group of columns that are concatenated.
To make it clear, here's the current result
And What I want is something like this:
Current code
public class Test_subReport {
protected static JasperPrint jp;
protected static JasperReport jr;
protected static Map params = new HashMap();
protected static DynamicReport dr;
public static void main(String args[]) throws SQLException, ColumnBuilderException, ClassNotFoundException {
Test_subReport t = new Test_subReport();
t.createReport();
}
public void createReport() throws SQLException, ColumnBuilderException, ClassNotFoundException {
ArrayList<Fruit> createMockDataset = createMockDataset();
Style titleStyle = new Style();
titleStyle.setHorizontalAlign(HorizontalAlign.CENTER);
titleStyle.setFont(Font.ARIAL_SMALL_BOLD);
Style dataStyle = new Style();
dataStyle.setHorizontalAlign(HorizontalAlign.CENTER);
dataStyle.setFont(Font.ARIAL_SMALL);
dataStyle.setBlankWhenNull(true);
final List items = SortUtils.sortCollection(createMockDataset, Arrays.asList(new String[]{"name", "description"}));
FastReportBuilder drb = new FastReportBuilder();
drb.setTemplateFile("templatePortrait.jrxml", true, true, true, true);
drb.addColumn("name", "name", String.class.getName(), 30, dataStyle)
.addColumn("description", "description", String.class.getName(), 50, dataStyle)
.setTitle("Report")
.setSubtitle("")
.setPrintBackgroundOnOddRows(true)
.setUseFullPageWidth(true);
drb.addGroups(2);
try {
drb.addField("evaluations", List.class.getName());
drb.addSubreportInGroupHeader(1, createSubreport("Evaluations"));
} catch (Exception ex) {
Logger.getLogger(Test_subReport.class.getName()).log(Level.SEVERE, null, ex);
}
DynamicReport dynamicReport = drb.build();
dynamicReport.setTitleStyle(titleStyle);
HashMap parametros = new HashMap();
parametros.put("dataRelatorio", MyTools.getDataPorExtenso());
doReport(dynamicReport, items, parametros);
}
public void doReport(final DynamicReport _report, final Collection _data, HashMap parametros) {
try {
JRDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(_data);
JasperPrint jasperPrint = DynamicJasperHelper.generateJasperPrint(_report, new ClassicLayoutManager(), beanCollectionDataSource, parametros);
JasperViewer.viewReport(jasperPrint);
} catch (JRException ex) {
ex.printStackTrace();
}
}
private DynamicReport createHeaderSubreport(String title) throws Exception {
FastReportBuilder rb = new FastReportBuilder();
DynamicReport dr = rb
.addColumn("id", "id", Integer.class.getName(), 100)
.addColumn("score", "score", Double.class.getName(), 50)
.setMargins(5, 5, 20, 20)
.setUseFullPageWidth(true)
.setWhenNoDataNoPages()
.setTitle(title)
.build();
return dr;
}
private Subreport createSubreport(String title) throws Exception {
SubReportBuilder srb = new SubReportBuilder();
srb.setDynamicReport(createHeaderSubreport(title), new ClassicLayoutManager())
.setStartInNewPage(true)
.setDataSource(DJConstants.DATA_SOURCE_ORIGIN_FIELD, DJConstants.DATA_SOURCE_TYPE_COLLECTION, "evaluations");
return srb.build();
}
public ArrayList<Fruit> createMockDataset() {
ArrayList<Fruit> fruits = new ArrayList<>();
Fruit f1 = new Fruit();
f1.name = "Apple X1";
f1.description = "Yummy yummy apple for the stackoverflow readers 1";
Fruit f2 = new Fruit();
f2.name = "Apple Ag";
f2.description = "Yummy yummy apple for the stackoverflow readers 2";
Fruit f3 = new Fruit();
f3.name = "Apple Mn";
f3.description = "Yummy yummy apple for the stackoverflow readers 3";
Fruit f4 = new Fruit();
f4.name = "Apple O2";
f4.description = "Yummy yummy apple for the stackoverflow readers 4";
//Evaluations for f1
for (int i = 0; i < 4; i++) {
Evaluation e = new Evaluation();
e.id = i;
e.score = Math.random() * 10;
f1.evaluations.add(e);
}
//evaluations for f4
for (int i = 0; i < 4; i++) {
Evaluation e = new Evaluation();
e.id = i;
e.score = Math.random() * 10;
f4.evaluations.add(e);
}
fruits.add(f1);
fruits.add(f2);
fruits.add(f3);
fruits.add(f4);
return fruits;
}
public class Fruit {
public String name;
public String description;
public ArrayList<Evaluation> evaluations = new ArrayList<Evaluation>();
public Fruit() {
}
public Fruit(String name, String description) {
this.name = name;
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public ArrayList<Evaluation> getEvaluations() {
return evaluations;
}
public void setEvaluations(ArrayList<Evaluation> evaluations) {
this.evaluations = evaluations;
}
}
public class Evaluation {
public int id;
public double score;
public Evaluation() {
}
public Evaluation(int id, double score) {
this.id = id;
this.score = score;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
}
}
Probably there isn't way to implement desired behavior using subreports.
I guess, that the best way to do it is to use just groups, but data model should be a bit modified for that.
Here is my solution:
public class Test_subReport {
protected static JasperPrint jp;
protected static JasperReport jr;
protected static Map params = new HashMap();
protected static DynamicReport dr;
public static void main(String args[]) throws SQLException, ColumnBuilderException, ClassNotFoundException {
Test_subReport t = new Test_subReport();
t.createReport();
}
public void createReport() throws SQLException, ColumnBuilderException, ClassNotFoundException {
List<DataWrapper> createMockDataset = wrapData(createMockDataset());
Style titleStyle = new Style();
titleStyle.setHorizontalAlign(HorizontalAlign.CENTER);
titleStyle.setFont(Font.ARIAL_SMALL_BOLD);
Style dataStyle = new Style();
dataStyle.setHorizontalAlign(HorizontalAlign.CENTER);
dataStyle.setFont(Font.ARIAL_SMALL);
dataStyle.setBlankWhenNull(true);
final List items = SortUtils.sortCollection(createMockDataset, Arrays.asList(new String[]{"name", "description"}));
FastReportBuilder drb = new FastReportBuilder();
drb.setTemplateFile("templatePortrait.jrxml", true, true, true, true);
drb.addColumn("name", "name", String.class.getName(), 30, dataStyle)
.addColumn("description", "description", String.class.getName(), 100, dataStyle)
.addColumn("id", "id", Integer.class.getName(), 30, dataStyle)
.addColumn("score", "score", Double.class.getName(), 30, false, "$ #.00", dataStyle)
.setTitle("Report")
.setWhenNoDataNoPages()
.setAllowDetailSplit(false)
.setUseFullPageWidth(true);
drb.addGroups(2);
DynamicReport dynamicReport = drb.build();
dynamicReport.setTitleStyle(titleStyle);
HashMap parametros = new HashMap();
parametros.put("dataRelatorio", MyTools.getDataPorExtenso());
doReport(dynamicReport, items, parametros);
}
public void doReport(final DynamicReport _report, final Collection _data, HashMap parametros) {
try {
JRDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(_data);
JasperPrint jasperPrint = DynamicJasperHelper.generateJasperPrint(_report, new ClassicLayoutManager(), beanCollectionDataSource, parametros);
JasperViewer.viewReport(jasperPrint);
} catch (JRException ex) {
ex.printStackTrace();
}
}
public List<DataWrapper> wrapData(List<Fruit> fruits) {
List<DataWrapper> dataList = new ArrayList<>();
for (Fruit fruit : fruits) {
if (fruit.getEvaluations().isEmpty()) {
dataList.add(new DataWrapper(fruit.name, fruit.description, null, null));
} else {
for (Evaluation evaluation : fruit.getEvaluations()) {
dataList.add(new DataWrapper(fruit.name, fruit.description, evaluation.id, evaluation.score));
}
}
}
return dataList;
}
public List<Fruit> createMockDataset() {
ArrayList<Fruit> fruits = new ArrayList<>();
Fruit f1 = new Fruit();
f1.name = "Apple X1";
f1.description = "Yummy yummy apple for the stackoverflow readers 1";
Fruit f2 = new Fruit();
f2.name = "Apple Ag";
f2.description = "Yummy yummy apple for the stackoverflow readers 2";
Fruit f3 = new Fruit();
f3.name = "Apple Mn";
f3.description = "Yummy yummy apple for the stackoverflow readers 3";
Fruit f4 = new Fruit();
f4.name = "Apple O2";
f4.description = "Yummy yummy apple for the stackoverflow readers 4";
//Evaluations for f1
for (int i = 0; i < 4; i++) {
Evaluation e = new Evaluation();
e.id = i;
e.score = Math.random() * 10;
f1.evaluations.add(e);
}
//evaluations for f4
for (int i = 0; i < 4; i++) {
Evaluation e = new Evaluation();
e.id = i;
e.score = Math.random() * 10;
f4.evaluations.add(e);
}
fruits.add(f1);
fruits.add(f2);
fruits.add(f3);
fruits.add(f4);
return fruits;
}
public class Fruit {
public String name;
public String description;
public ArrayList<Evaluation> evaluations = new ArrayList<Evaluation>();
public Fruit() {
}
public Fruit(String name, String description) {
this.name = name;
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public ArrayList<Evaluation> getEvaluations() {
return evaluations;
}
public void setEvaluations(ArrayList<Evaluation> evaluations) {
this.evaluations = evaluations;
}
}
public class Evaluation {
public int id;
public double score;
public Evaluation() {
}
public Evaluation(int id, double score) {
this.id = id;
this.score = score;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
}
public class DataWrapper {
public String name;
public String description;
public Integer id;
public Double score;
public DataWrapper() {
}
public DataWrapper(String name, String description, Integer id, Double score) {
this.name = name;
this.description = description;
this.id = id;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Double getScore() {
return score;
}
public void setScore(Double score) {
this.score = score;
}
}
}
And here is the result:
Feel free to ask if you have some question.

Adding information into an array with super classes

The problem I'm having is with the superclass. I can't change the new Property(...) to another class called House. The only difference is the information in them, but once I change it I am getting an error stating that the constructor doesn't match but I thought that the super() should pass the information on.
This is how my Array is set up:
public static void main(String[] args) {
Property [] Properties = new Property[25];
Properties[0] = new Property (1001, 200, "58 Lackagh Park", "Dungiven", "BT47 4ND", new MyDate(15,05,2018), 5000.00, 800.50, 40.50);
Properties[1] = new Property (1002, 500, "24 Jop Lane", "Kelflar", "VT57 5LP", new MyDate(10,06,2018), 12000.00, 1000.00, 60.00);
Properties[2] = new Property (1003, 100, "Lot B", "Bandlebop", "LU49 3JU", new MyDate(01,07,2018), 450.00, 800.00, 50.50);
Properties[3] = new Property (1004, 200, "12 Back Lane", "Galafray", "GA1 1Fy", new MyDate(05,12,2018), 50000.00, 1000.00, 80.00);
Properties[4] = new Property (1005, 200, "43 Pop Street", "Jundar", "BY78 1JH", new MyDate(11,12,2018), 2500.00, 600.50, 32.90);
Properties[5] = new Property (1006, 200, "123 Fake Street", "Dunlem", "BL09 4PL", new MyDate(21,03,2018), 65000.00, 700.50, 56.50);
Properties[6] = new Property (1007, 200, "09012 Bakers Field", "Bristol", "LO87 D0N", new MyDate(15,05,2018), 5000.00, 200.50, 40.50);
Properties[7] = new Property (1008, 200, "Unit B high Street", "LA", "LA58 7NL", new MyDate(18,11,2018), 20000.00, 1000.00, 90.00);
Properties[8] = new Property (1009, 200, "1 Flabbergast Park", "Nubb", "HJ98 7NH", new MyDate(10,03,2018), 4958.00, 900.20, 20.50);
Properties[9] = new Property (1010, 200, "29 Bakers Field", "London Town", "HU84 2JO", new MyDate(02,05,2018), 1234.00, 800.00, 40.50);
Properties[10] = new Property (1011, 200, "20 Peliper Lane", "Dungiven", "BT47 4FE", new MyDate(15,05,2018), 4321.00, 900.00, 20.00);
Here is the Property class:
public class Property {
private int PropertyNumber, SquareFoot;
private String Address,Town,PostCode;
private MyDate DateListed;
public double Price;
private double Rates;
private double PricePerSquareFoot;
public Property() {
PropertyNumber = 0;
SquareFoot = 0;
Address = "";
Town = "";
PostCode = "";
DateListed = new MyDate();
Price = 0.0;
Rates = 0.0;
PricePerSquareFoot = 0.0;
}
public Property(int PropertyNumber, int SquareFoot, String Address, String Town, String PostCode, MyDate DateListed, double Price, double rates, double PricePerSquareFoot)
{
super();
this.PropertyNumber = PropertyNumber;
this.SquareFoot = SquareFoot;
this.Address = Address;
this.Town = Town;
this.PostCode = PostCode;
this.DateListed = DateListed;
this.Price = Price;
this.Rates = Rates;
this.PricePerSquareFoot = PricePerSquareFoot;
}
//--------Getters and setters----------------//
public void setPropertyNumber(int PropertyNumber)
{
this.PropertyNumber = PropertyNumber;
}
public int getPropertyNumber()
{
return PropertyNumber;
}
public void setSquareFoot(int SquareFoot)
{
this.SquareFoot = SquareFoot;
}
public int getSquareFoot()
{
return SquareFoot;
}
public void setAddress(String Address)
{
this.Address = Address;
}
public String getAddress()
{
return Address;
}
public void setTown( String Town)
{
this.Town = Town;
}
public String getTown()
{
return Town;
}
public void setPostcode( String PostCode)
{
this.PostCode = PostCode;
}
public String GetPostcode()
{
return PostCode;
}
public void setDateListed(MyDate DateListed)
{
this.DateListed = DateListed;
}
public MyDate getDateListed()
{
return DateListed;
}
public void setPrice(double Price)
{
this.Price = Price;
}
public double getPrice()
{
return Price;
}
public void setRates(double Rates)
{
this.Rates = Rates;
}
public double getRates()
{
return Rates;
}
public void setPricePerSquareFoot(double PricePerSqaureFoot)
{
this.PricePerSquareFoot = PricePerSquareFoot;
}
public double getPricePerSquareFoot()
{
return PricePerSquareFoot;
}
And this is what I am trying to put into the array along with the property information such as Property number price etc:
public class House extends Residential {
private int Garden;
private int Garage;
public House() {
super();
Garage = 0;
Garden = 0;
}
public House(int Garage, int garden) {
super();
this.Garage = 0;
this.Garden = 0;
}
public void setGarage(int Garage)
{
this.Garage = Garage;
}
public int getGarage()
{
return Garage;
}
public void setGarden(int Garden)
{
this.Garden = Garden;
}
public int getGarden()
{
return Garden;
}
.......
This is the residential class
public class Residential extends Property
{
private int NumberOfBedrooms;
private int NumberOfBathrooms;
public Residential()
{
super();
NumberOfBedrooms = 0;
NumberOfBathrooms = 0;
}
public void setNumberOfBedrooms(int NumberOfBedrooms)
{
this.NumberOfBedrooms = NumberOfBedrooms;
}
public int getNumberOfBedrooms()
{
return NumberOfBedrooms;
}
public void setNumberOfBathrooms(int NumberOfBathrooms)
{
this.NumberOfBathrooms = NumberOfBathrooms;
}
public int getNumberOfBathrooms()
{
return NumberOfBathrooms;
}
public Residential(int NumberOfBedrooms, int NumberOfBathrooms)
{
super();
NumberOfBedrooms = 0;
NumberOfBathrooms = 0;
}

Jackson: Serialise ArrayList not working?

I am referring to this example here to serialize my object.
I have this initially and it works.
public class MyClass implements Serializable {
private String mediaitem_id;
private String customer_id;
private int quantity;
public MyClass(String item, String customer, int quantity){
this.mediaitem_id = item;
this.customer_id = customer;
this.quantity = quantity;
}
public String toJson(){
ObjectMapper mapper = new ObjectMapper();
try{
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CASE);
return mapper.writeValueAsString(this);
}catch(Exception ex){
log.error("Error converting MyClass to json " + this, ex);
}
return "";
}
}
MyClass myClass = new MyClass("1234", "23234", 5);
myClass.toJson() gives the below, which is what I want:
{ mediaitem_id: '1234', customer_id: '23234', quantity: 5 }
But now I need to add an arraylist to the class and need to serialise it as well, so I add a new class Account:
public static class Account implements Serializable {
public String accountname;
public String accountid;
public Account(String accountname, String accountid) {
this.accountname = accountname;
this.accountid = accountid;
}
}
public class MyClass implements Serializable {
private String mediaitem_id;
private String customer_id;
private int quantity;
private List<Account> accounts = new ArrayList<>();
public MyClass(String item, String customer, int quantity){
this.mediaitem_id = item;
this.customer_id = customer;
this.quantity = quantity;
}
public void addAccount(String accountname, String accountid) {
Account anAccount = new Account(accountname, accountid);
accounts.add(anAccount);
}
public String toJson(){
ObjectMapper mapper = new ObjectMapper();
try{
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CASE);
return mapper.writeValueAsString(this);
}catch(Exception ex){
log.error("Error converting MyClass to json " + this, ex);
}
return "";
}
}
MyClass myClass = new MyClass("1234", "23234", 5);
myClass.addAccount("acc-01", "a001");
myClass.addAccount("acc-02", "a002");
myClass.toJson() still gives the same:
{ mediaitem_id: '1234', customer_id: '23234', quantity: 5 }
What am I missing now?
I wanted to get something like:
{ mediaitem_id: '1234', customer_id: '23234', quantity: 5, accounts: [{accountname: 'acc-01', accountid: 'a001'}, {accountname: 'acc-02', accountid: 'a002'}]}
I recommed add your getter and setter for all property in your MyClass .
public String getMediaitem_id() {
return mediaitem_id;
}
public void setMediaitem_id(String mediaitem_id) {
this.mediaitem_id = mediaitem_id;
}
public String getCustomer_id() {
return customer_id;
}
public void setCustomer_id(String customer_id) {
this.customer_id = customer_id;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public List<Account> getAccounts() {
return accounts;
}
public void setAccounts(List<Account> accounts) {
this.accounts = accounts;
}

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.

Point Of Sales - Stuck on arrays

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;
}

Categories