Reduse integer everytime an new object is added to arraylist - java

I have a class of Person with an ArrayList of the class Groceries.
Let's name the Arraylist shoppingBag.
Student and Groceries has one field each, int money and int price.
The specific amount of money and price is up to you when initializing new objects.
So every time a Person adds an object of Groceries to his shoppingBag, the amount of money he has needs to be reduced with the total price of groceries added to the bag.
How do you do that?

So, let my try to understand what you want (as I do the same for my clients)
You have a class Groceries with price field:
class Groceries {
private int price;
public Groceries(int price) {
this.price = price;
}
public int getPrice() {
return price;
}
#Override
public String toString() {
return "Groceries{" +
"price=" + price +
'}';
}
}
And class person with int money filed and shopping bag field as List of Groceries:
class Person {
private List<Groceries> shoppingBag = new ArrayList<>();
private int money;
public Person(int money) {
this.money = money;
}
public List<Groceries> getShoppingBag() {
return shoppingBag;
}
public int getMoney() {
return money;
}
}
Firstly you create an instance of Person with some mount of money: Person person = new Person(150);
And then each time when you add a groceries to the shopping bag, like person.getShoppingBag().add(new Groceries(10)); you do want to reduce amount of money from the person instance.
So, If I am correct, you need to implement several things:
1) You should forbid adding groceries to the shopping bag with the way described before. We need to throw an exception when someone tries to add an element to the List via getter. It can be implemented using an Unmodifiable copy of your list:
public List<Groceries> getShoppingBag() {
List<Groceries> bag = new UnmodifiableArrayList<>(shoppingBag.toArray(new Groceries[shoppingBag.size()]), shoppingBag.size());
return bag;
}
or a little bit nicely and shortly using Guava:
public List<Groceries> getShoppingBag() {
List<Groceries> bag = ImmutableList.copyOf(shoppingBag);
return bag;
}
2) Add a method that will add a groceries directly. You can also throw an exception if there is no enough money to not have negative balance:
public void addToShoppingBag(Groceries groceries) {
if (0 > money - groceries.getPrice()) {
throw new IllegalStateException("You have not enough money!");
}
shoppingBag.add(groceries);
money -= groceries.getPrice();
}
3) Probably you will need to have possibility to add some money:
private void addMoney(int amout) {
money += amout;
}
Please see the completely demo example:
class Demo {
public static void main(String[] args) throws IOException {
Person person = new Person(42);
try {
System.out.println(person.getMoney());
person.addToShoppingBag(new Groceries(12));
person.addToShoppingBag(new Groceries(20));
person.addToShoppingBag(new Groceries(5));
System.out.println(person.getMoney());
System.out.println(person.getShoppingBag());
person.getShoppingBag().add(new Groceries(1));
} catch (UnsupportedOperationException e) {
e.printStackTrace();
}
try {
person.addToShoppingBag(new Groceries(66));
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
}
class Person {
private List<Groceries> shoppingBag = new ArrayList<>();
private int money;
public Person(int money) {
this.money = money;
}
public List<Groceries> getShoppingBag() {
List<Groceries> bag = ImmutableList.copyOf(shoppingBag);
return bag;
}
public void addToShoppingBag(Groceries groceries) {
if (0 > money - groceries.getPrice()) {
throw new IllegalStateException("You have not enough money!");
}
shoppingBag.add(groceries);
money -= groceries.getPrice();
}
private void addMoney(int amout) {
money += amout;
}
public int getMoney() {
return money;
}
}
class Groceries {
private int price;
public Groceries(int price) {
this.price = price;
}
public int getPrice() {
return price;
}
#Override
public String toString() {
return "Groceries{" +
"price=" + price +
'}';
}
}
PS: Please next time describe some examples of code and demos to get an answer :)

Related

Strategy design pattern Example?

Following is stretagy design pattern example take from here.
First of all we will create the interface for our strategy, in our case to pay the amount passed as argument.
public interface PaymentStrategy {
public void pay(int amount);
}
public class CreditCardStrategy implements PaymentStrategy {
private String name;
private String cardNumber;
private String cvv;
private String dateOfExpiry;
public CreditCardStrategy(String nm, String ccNum, String cvv, String expiryDate){
this.name=nm;
this.cardNumber=ccNum;
this.cvv=cvv;
this.dateOfExpiry=expiryDate;
}
#Override
public void pay(int amount) {
System.out.println(amount +" paid with credit/debit card");
}
}
public class PaypalStrategy implements PaymentStrategy {
private String emailId;
private String password;
public PaypalStrategy(String email, String pwd){
this.emailId=email;
this.password=pwd;
}
#Override
public void pay(int amount) {
System.out.println(amount + " paid using Paypal.");
}
}
public class Item {
private String upcCode;
private int price;
public Item(String upc, int cost){
this.upcCode=upc;
this.price=cost;
}
public String getUpcCode() {
return upcCode;
}
public int getPrice() {
return price;
}
}
public class ShoppingCart {
//List of items
List<Item> items;
public ShoppingCart(){
this.items=new ArrayList<Item>();
}
public void addItem(Item item){
this.items.add(item);
}
public void removeItem(Item item){
this.items.remove(item);
}
public int calculateTotal(){
int sum = 0;
for(Item item : items){
sum += item.getPrice();
}
return sum;
}
public void pay(PaymentStrategy paymentMethod){
int amount = calculateTotal();
paymentMethod.pay(amount);
}
}
public class ShoppingCartTest {
public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();
Item item1 = new Item("1234",10);
Item item2 = new Item("5678",40);
cart.addItem(item1);
cart.addItem(item2);
//pay by paypal
cart.pay(new PaypalStrategy("myemail#example.com", "mypwd"));
//pay by credit card
cart.pay(new CreditCardStrategy("Pankaj Kumar", "1234567890123456", "786", "12/15"));
}
}
I want to ask what is use of strategy pattern here?Once we have created a strategy in main.We have access to Strategy class now.We can directly call pay() method from there?Why do we need interface , all which does is call a method?
1. I want to ask what is use of strategy pattern here?
The answer is the user who has the ShoppingCart (ShoppingCart cart = new ShoppingCart();)
2. We can directly call pay() method from there?
I don't know exactly you mean
3. Why do we need interface , all which does is call a method?
We need the interface PaymentStrategy because we need use Polymorphism to implement many way to pay (paypal or credit card), let's change the source a bit and you can see clearer:
public class ShoppingCart {
// other functions
public void pay(PaymentStrategy paymentMethod, int amount){
paymentMethod.pay(amount);
}
public void payWithStrategy() {
int amount = calculateTotal();
if (amount > 10000) { // because your credit card limit is 10000$ so you must use paypal
pay(new PaypalStrategy("myemail#example.com", "mypwd"), amount);
}
else { // you really like credit card so when the money lower than the card limit, you always choose it
pay(new CreditCardStrategy("Pankaj Kumar", "1234567890123456", "786", "12/15"), amount);
}
}
}
public class ShoppingCartTest {
public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();
Item item1 = new Item("1234",10);
Item item2 = new Item("5678",40);
cart.addItem(item1);
cart.addItem(item2);
cart.payWithStrategy();
}
}

How to get a count from hashmap?

I have a question about hashmap,
I have a class product:
public class product{
private String libele;
and also a class special product:
public class SpecialProd extends Product{
private HashMap<Product, Price> comp = new HashMap<Product, Price>();
public HashMap<Product, Price> getComp() {
return comp;
}
}
The problem is that i need to know how much products i have in stock, the total amount of the products and how much for every product:
so i used this code in the class storage:
public class Storage{
private HashMap<Product, Price> port = new HashMap<Product, Price>();
public void total (){
int nombre=0;
int total = 0;
int i=0;
for (Product p:port.keySet()){
if (port.containsKey(a)){
// ++nombre;
}
total = port.size();
System.out.println(+nombre+ "of" +a.getLibele());
}
System.out.println("total products:" +total);
}
// this is an intern class
static class Part{
private int price;
public Price(int price) {
this.price= price;
}
public int getprice() {
return price;
}
public void setPrice(int price) {
this.price= price;
}
}
}
i couldn't get the count of every product and the total prices.
Any ideas please?
You can try enumerating the HashMap and get the desired values.
int count=0;
for(p : port.keySet()){
count ++;
price = price + port.get(a);
}

About Java object sort

I experience some issues about sorting price in Java.
I want from high price to low price and from low to high price respectively in my ArrayList.
ArrayList<orderbook> buyerlist=new ArrayList<orderbook>();
I want buyerlist to sort object sequence by price. I tried below but it does not works.
buyerlist.add(new orderbook(orderrecord.get(i).getSide(),orderrecord.get(i).getVolume(),orderrecord.get(i).getPrice()));
Collections.sort(arraylist);
ArrayList<orderbook> sellerlist=new ArrayList<orderbook>();
I want sellerlist can sort object sequence by price
here is my constructor
public class orderbook {
// here i defined three object of this constructor.
// i want sorting this sequence by price. from high to low and low to high respectively.
String side;
int volume;
double price;
public orderbook(String side,int volume,double price){
this.side=side;
this.volume=volume;
// compare price is low then 0 will throw exception
if (volume < 0) {
throw new IllegalArgumentException("volume size illegal");
}
this.price=price;
if (price < 0) {
throw new IllegalArgumentException("price > 0 require");
}
}
public String getSide() {
return side;
}
public void setSide(String side) {
this.side = side;
}
public int getVolume() {
return volume;
}
public void setVolume(int volume) {
this.volume = volume;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
If you have orderbooks in some Collection for example ArrayList, then you can sort them tis way:
Collections.sort(orderBooks, new Comparator<orderbook> {
#Override
public int compare(orderbook ob1, orderbook ob2) {
return o1.getPrice() - o2.getPrice();
}
});

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.

How to create method for withdrawal from store and deliverance to store

I am studying java by myself and I want to get help on exercise which i am doing myself.
The class is called Product which used for representing a product that a small company sells.
It should be possible to store the following information about each product.
The class should have the following methods:
A constructor
A method that returns the units of items in store
A method for deliverance to the store (increases the units of this product)
A method for withdrawal from the store (decreases the units of this product)
Please note that if one of the methods changes the stored items below the order point a message should be printed. It should also be impossible to have a negative amount of items.
I HAVE PROBLEM WITH METHODS. PLEASE TAKE A LOOK MY CODE AND GIVE ME SOME HINTS. I WILL APPRECIATE ALL RESPONDS.
THANK YOU.
Here is my program:
public class Product {
private int productNumber;
private String productName;
private float price;
private int orderPoint;
private int unitsInStore;
private String proDescription;
public Product(int num, String name, float price, int order, int units, String description){
this.productNumber = num;
this.productName = name;
this.price = price;
this.orderPoint = order;
this.unitsInStore = units;
this.proDescription = description;
}
public int getProductNumber() {
return productNumber;
}
public void setProductNumber(int productNumber) {
this.productNumber = productNumber;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public int getOrderPoint() {
return orderPoint;
}
public void setOrderPoint(int orderPoint) {
this.orderPoint = orderPoint;
}
// a method returns the units in store
public int getUnitsInStore() {
return unitsInStore;
}
public void setUnitsInStore(int unitsInStore) {
this.unitsInStore = unitsInStore;
}
public String getProDescription() {
return proDescription;
}
public void setProDescription(String proDescription) {
this.proDescription = proDescription;
}
public int deliveranceToStore(int store){
unitsInStore = unitsInStore + store;
return unitsInStore ++ ;
}
public int withdrawal(int store){
unitsInStore = store - unitsInStore;
return unitsInStore --;
}
}
The deliveranceToStore method isn't correct. Why are you calling the method recursively?
The method can simply be:
public int deliveranceToStore(int store) {
unitsInStore = unitsInStore + store;
return unitsInStore;
}
If there is no need to return the number of units in store with this call, you should have the return type as void (i.e., if updating the count is sufficient):
public void deliveranceToStore(int store) {
unitsInStore = unitsInStore + store;
}
For withdrawal, you need a similar strategy where unitsInStore is updated:
public void withdrawal(int units) {
if(unitsInStore - units >= 0) {
unitsInStore = unitsInStore - units;
} else {
System.out.println("Unable to withdraw. Insufficient units in store.");
}
}
You can also make the withdrawal method return a boolean which tells whether the withdrawal action was successful. The method, in that case, may look like:
public boolean withdrawal(int units) {
if(unitsInStore - units >= 0) {
unitsInStore = unitsInStore - units;
return true;
} else {
System.out.println("Unable to withdraw. Insufficient units in store.");
return false;
}
}

Categories