I got 5 classes, and 4 of them are working as intended.
I'm an absolut beginer with java and I hope someone can provide me with help.
its a little application to make orders and bundle orders.
my problem is the class bundleItem.
I expect to get the value of all items with a discount added to them, but I allways get negative return values.
Here are my classes
class Order
package testateins;
import java.util.ArrayList;
public class Order {
private ArrayList<Item> allOrders;
public Order(){
this.allOrders = new ArrayList<Item>();
}
public void addItem(Item item) {
this.allOrders.add(item);
}
public void removeItem(Item item) {
this.allOrders.remove(item);
}
public double getTotalprice(){
double totalprice = 0;
for(Item element : allOrders) {
totalprice += element.getPrice();
}
return totalprice;
}
public void printItems() {
for(Item element : allOrders) {
element.print();
}
}
}
Class Item
package testateins;
public abstract class Item{
String description;
double price;
public Item(String description) {
this.description = description;
}
public abstract double getPrice();
public void setItem() {
}
public void print() {
System.out.println("Beschreibung " + description);
}
}
class ProductItem
package testateins;
public class ProductItem extends Item{
public double pricePerUnit;
public double amount;
public double price;
public ProductItem(String description, int pricePerUnit, int amount) {
super(description);
this.pricePerUnit = pricePerUnit;
this.amount = amount;
this.price = amount * pricePerUnit;
}
public void print() {
System.out.println("Beschreibung " + description);
System.out.println("menge " + amount);
System.out.println("Preis pro Einheit " + pricePerUnit);
System.out.println("Gesammtpreis " + price);
}
public double getPrice() {
return this.price;
}
}
class ServiceItem
package testateins;
public class ServiceItem extends Item{
public double price;
public ServiceItem(String description, Integer packageprice) {
super(description);
this.price = packageprice;
}
public void print() {
System.out.println("Beschreibung " + description);
System.out.println("Servicepreis " + price);
}
public double getPrice() {
return this.price;
}
}
class BundleItem(my problemclass)
package testateins;
import java.util.ArrayList;
public class BundleItem extends Item {
private double rabatt;
private ArrayList<Item> allOrders;
public BundleItem(String description, double rabatt) {
super(description);
this.allOrders = new ArrayList<Item>();
setrabatt(rabatt);
}
public void setrabatt(double rabatt) {
this.rabatt = rabatt;
}
public double getrabatt() {
return this.rabatt;
}
public void addItem(Item item) {
if(item instanceof ProductItem || item instanceof ServiceItem) {
this.allOrders.add(item);
}
}
#Override
public double getPrice() {
double result = 0;
double sum = 0;
double discount = (rabatt/100);
for(Item element : allOrders) {
result+=element.getPrice();
}
return sum - (result * discount);
}
public void print() {
super.print();
System.out.println(rabatt);
for(Item element: allOrders) {
element.print();
}
}
}
and my testing class which returns negative discounts, the important part is after "part 2"
package testateins;
public class Testing {
public static void main(String[] args) {
ServiceItem wischen = new ServiceItem("wischen", 20);
System.out.println(wischen.description);
System.out.println(wischen.price);
System.out.println("___________________________");
ProductItem kuchen = new ProductItem("kuchen", 3, 15);
System.out.println(kuchen.description);
System.out.println(kuchen.amount);
System.out.println(kuchen.pricePerUnit);
System.out.println(kuchen.price);
System.out.println("___________________________");
Order simpleOrder = new Order();
simpleOrder.addItem(wischen);
simpleOrder.addItem(kuchen);
simpleOrder.addItem(kuchen);
simpleOrder.printItems();
System.out.println("___________________________");
System.out.println("totalpreis:");
System.out.println(simpleOrder.getTotalprice());
//part 2
System.out.println("--------uebung 2------------.-");
Order BundleOrder = new Order();
ProductItem heft = new ProductItem("Heft", 1, 10);
ProductItem stift = new ProductItem("Stift", 1, 10);
BundleItem Discounteins = new BundleItem("Discounteins(50)", 50);
BundleItem Discountzwei = new BundleItem("Discountzwei(50)", 50);
BundleItem Discountdrei = new BundleItem("Discounteins(10)", 10);
Discounteins.addItem(heft);
Discounteins.addItem(stift);
Discountzwei.addItem(Discounteins);
Discountzwei.addItem(wischen);
Discountzwei.addItem(wischen);
Discountdrei.addItem(wischen);
Discountdrei.addItem(wischen);
BundleOrder.addItem(Discountzwei);
BundleOrder.addItem(Discounteins);
BundleOrder.printItems();
System.out.println(BundleOrder.getTotalprice());
System.out.println("---------------------------.-");
Discounteins.setrabatt(50);
System.out.println(Discounteins.getrabatt());
BundleOrder.printItems();
System.out.println("---------------------------.---");
System.out.println(BundleOrder.getTotalprice());
System.out.println("---------------------------.----");
}
}
Your sum is always zero, that's why you always get negative values.
I suppose you intended to do something like this:
#Override
public double getPrice() {
double sum = 0;
double discount = (rabatt / 100);
for(Item element : allOrders) {
sum += element.getPrice();
}
return sum - (sum * discount);
}
Try replacing
return sum - (result * discount);
with
return result-(result * discount);
and remove the sum variable that is not used. Now
(result * discount)
will give you the total discount. And Subtracting it from result will give you the actual amount after discounts
Related
I want to read and map the following formatted lines into java bean
80 : (1,53.38,€45) (2,88.62,€98) (3,78.48,€3) (4,72.30,€76) (5,30.18,€9)
7 : (1,10.02,€5) (2,8.2,€9) (3,7.8,€2) (4,7.0,€6) (5,3.18,€9)
So here the digit before : will be captured as a int value and will be mapped on totalWeight and repetive patterns like (1,53.38,€45) will be mapped to items
Here is my java bean
public class Package {
private double maxWeigh; \\ so the digit value before : will be here
private List<Product> products; \\ (1,53.38,€45) will be parsed to product class
public double getMaxWeigh() {
return maxWeigh;
}
public void setMaxWeigh(double maxWeigh) {
this.maxWeigh = maxWeigh;
}
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
}
Here is my product class
public class Product {
private int index;
private double weight;
private double cost;
private String currencySymbol;
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public double getCost() {
return cost;
}
public void setCost(double cost) {
this.cost = cost;
}
public String getCurrencySymbol() {
return currencySymbol;
}
public void setCurrencySymbol(String currencySymbol) {
this.currencySymbol = currencySymbol;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
This is what i tried so far but this is for only products part i want to capture whole line at once
\\((\\d+),(\\d+\\.?\\d*?),€?(\\d+)\\)
Here is a code that lets you iterate over each token (a,b,c) and retrieve their members.
It uses named capturing groups.
import java.util.regex.*;
public static void main(String[] args) {
Pattern headPattern = Pattern.compile("^(\\d+).*");
Pattern tailPattern = Pattern.compile("\\((?<p1>\\d),(?<p2>\\d+\\.\\d+),(?<p3>€\\d+)\\)");
Matcher m1 = headPattern.matcher("80 : (1,53.38,€45) (2,88.62,€98) (3,78.48,€3) (4,72.30,€76) (5,30.18,€9)");
Matcher m2 = tailPattern.matcher("80 : (1,53.38,€45) (2,88.62,€98) (3,78.48,€3) (4,72.30,€76) (5,30.18,€9)");
m1.matches();
System.out.println("p0 = " + m1.group(1));
while(m2.find()) {
System.out.println("token = " + m2.group());
System.out.println("p1 = " + m2.group("p1"));
System.out.println("p2 = " + m2.group("p2"));
System.out.println("p3 = " + m2.group("p3"));
}
}
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);
If i wanted to use a Dynamic Array List which is initializing class Worker can i add sub-classes that extend the Worker class and try to fill them with data like the following test class?.. whenever i try calling a certain function that one of the sub-classes have i get an error , I need to call these functions so how can i do it correctly?
public class Worker extends Person {
private int id;
Worker() {
}
Worker(int i) {
id = i;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String toString() {
return super.toString() + "ID: " + id + " ";
}
}
public class HourlyWorker extends Worker implements Annual {
private double rate;
private double AnnualPayment;
private double percentageIncrease;
HourlyWorker() {
}
HourlyWorker(double r) {
rate = r;
}
public double getAnnualPay(double Annualpayment) {
return Annualpayment = rate * 52 * 40;
}
public double getRate() {
return rate;
}
public void setRate(double rate) {
this.rate = rate;
}
public double getAnnualPayment() {
return AnnualPayment;
}
public void setAnnualPayment(double AnnualPayment) {
this.AnnualPayment = AnnualPayment;
}
public double getpercentageIncrease() {
return percentageIncrease;
}
public void setpercentageIncrease(double percentageIncrease) {
this.percentageIncrease = percentageIncrease;
}
public void increasePayment(double r) {
increasePayR(r);
}
public double increasePayR(double r) {
return rate = (AnnualPayment + getAnnualPay(r) * percentageIncrease) / 2080;
}
public String toString() {
return "Your rate : " + rate + " ";
}
}
public class SalariedWorker extends Worker implements Annual {
private double salary;
private double AnnualPayment;
private double percentageIncrease;
SalariedWorker() {
}
SalariedWorker(double s) {
salary = s;
}
public double getAnnualPay(double Annualpayment) {
return Annualpayment = salary * 12;
}
public void increasePayment(double r) {
increasePayS(r);
}
public double increasePayS(double r) {
return salary = (AnnualPayment + getAnnualPay(r) * percentageIncrease) / 12;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public double getAnnualPayment() {
return AnnualPayment;
}
public void setAnnualPayment(double AnnualPayment) {
this.AnnualPayment = AnnualPayment;
}
public double getpercentageIncrease() {
return percentageIncrease;
}
public void setpercentageIncrease(double percentageIncrease) {
this.percentageIncrease = percentageIncrease;
}
public String toString() {
return " ";
}
}
public class Test {
public static void main(String[] args) {
Scanner prompt = new Scanner(System.in);
ArrayList<Worker> Worker1 = new ArrayList<Worker>();
Worker1.add(new SalariedWorker());// is it alright to create a subclass object here?
Worker1.add(new SalariedWorker(1000.0));// index 1
Worker1.add(new HourlyWorker());// index 2
Worker1.add(new HourlyWorker(100.0));// index 3
System.out.println("Enter your monthly salary: ");
double salary = prompt.nextDouble();
Worker1.get(0).getSalary(salary);//gets me an error
System.out.println("Enter your hourly rate: ");
double HourlyRate = prompt.nextDouble();
System.out.println("Enter the Percentage Increase for a Salaried worker: ");
double PercentIncreaseS = prompt.nextDouble();
Worker1.get(0).getpercentageIncrease(PercentIncreaseS);//gets me an error
System.out.println("Your Increased payment is: ");
System.out.println("Enter the Percentage Increase for an Hourly worker: ");
double PercentIncreaseH = prompt.nextDouble();
}
}
You are getting the error because the Worker class does not have a getSalary() method.
You need to cast the objects in the list to the appropriate sub-class type.
For example:
SalariedWorker sw = (SalariedWorker) Worker1.get(0);
sw.getSalary(salary);
Problem with below code fragment is:
ArrayList<Worker> Worker1 = new ArrayList<Worker>();
Worker1.get(0).getSalary(salary);
get will return you the abstraction which doesn't have the getSalary(salary) method. All you have to do is to cast each with respective implementation class and the invoke the method on it.
Ex:
SalariedWorker sw = (SalariedWorker)Worker1.get(0);
I am new to Java and I am working on a project that works with calculating prices with/without employee discounts. After reading the following code could someone explain to me how I might go about changing the parent class method outputs from the child class in order to get the correct outputs for my program?
Parent Class (I am NOT allowed to edit this):
public class GroceryBill {
private Employee clerk;
private List<Item> receipt;
private double total;
private double internalDiscount;
public GroceryBill(Employee clerk) {
this.clerk = clerk;
receipt = new ArrayList<Item>();
total = 0.0;
internalDiscount = 0.0;
}
public void add(Item i) {
receipt.add(i);
total += i.getPrice();
internalDiscount += i.getDiscount();
}
public double getTotal() {
return Math.rint(total * 100) / 100.0;
}
public Employee getClerk() {
return clerk;
}
public void printReceipt() {
System.out.println(this);
}
private String valueToString(double value) {
value = Math.rint(value * 100) / 100.0;
String result = "" + Math.abs(value);
if(result.indexOf(".") == result.length() - 2) {
result += "0";
}
result = "$" + result;
return result;
}
public String receiptToString() {
String build = "items:\n";
for(int i = 0; i < receipt.size(); i++) {
build += " " + receipt.get(i);
if(i != receipt.size() - 1) {
build += "\n";
}
}
return build;
}
public String toString() {
return receiptToString() + "\ntotal: " + valueToString(total);
}
public String discountToString() {
return receiptToString() + "\nsub-total: " + valueToString(total) + "\ndiscount: " + valueToString(internalDiscount) + "\ntotal: " + valueToString(total - internalDiscount);
}
public static class Employee {
private String name;
public Employee(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public static class Item {
private String name;
private double price;
private double discount;
public Item(String name, double price, double discount) {
this.name = name;
this.price = price;
this.discount = discount;
}
public double getPrice() {
return price;
}
public double getDiscount() {
return discount;
}
private String valueToString(double value) {
String result = "" + Math.abs(value);
if(result.indexOf(".") == result.length() - 2) {
result += "0";
}
result = "$" + result;
return result;
}
public String toString() {
return name + " " + valueToString(price) + " (-" + valueToString(discount) + ")";
}
}
}
Here is my code:
public class DiscountBill extends GroceryBill
{
private int myDiscountCount;
private double myDiscountAmount;
private double myPrice;
public DiscountBill(Employee clerk, boolean preferred)
{
super(clerk);
String name = "";
double price = 0;
double discount = 0;
Object myItem = new Item(name, price, discount);
myPrice = ((GroceryBill.Item) myItem).getPrice() - ((GroceryBill.Item) myItem).getDiscount();
GroceryBill.Item myBill = new GroceryBill.Item(name, price, discount);
myDiscountAmount = myBill.getDiscount();
if (myDiscountAmount > 0 && preferred)
{
myDiscountCount++;
}
}
/*
public double getTotal()
{
Override goes here?
}
*/
public int getDiscountCount()
{
return myDiscountCount;
}
public double getDiscountAmount()
{
return myDiscountAmount;
}
public double getDiscountPercent()
{
return (myPrice / getDiscountCount()) * 100;
}
}
Lastly, here is the expected output:
P.S. Please let me know if I need to give more/less information and ways that I can clean up this post or make it easier to understand. If my question was too broad, please ask me what you don't understand about it and I'll try my best to tell you! Thank you!
I have an inventory program written to include an array and a method to calculate total cost for all inventory items entered. I now have to include a subclass that overrides the original to include "one unique feature". I created a new file named ItemDetails to set up for the subclasses of the original Item. I need to include one unique feature and calculate the value of the inventory and calculate a 5% restocking fee in this subclass. Do I just transfer some of the relevant lines into the other class? Or do I write some code twice? I don't know what to do next. Any help is useful. Thanks. This is what I have so far:
package inventory3;
public class ItemDetails extends Items
{
public static void override()
{
private String Name;
private double pNumber, Units, Price;
public ItemDetails()
{
}
}
}
This is the Item class file that it is supposed to override:
package inventory3;
import java.lang.Comparable;
public class Items implements Comparable
{
private String Name;
private double pNumber, Units, Price;
public Items()
{
Name = "";
pNumber = 0.0;
Units = 0.0;
Price = 0.0;
}
public int compareTo(Object item)
{
Items tmp = (Items) item;
return this.getName().compareTo(tmp.getName());
}
public Items(String productName, double productNumber, double unitsInStock, double unitPrice)
{
Name = productName;
pNumber = productNumber;
Units = unitsInStock;
Price = unitPrice;
}
//setter methods
public void setName(String n)
{
Name = n;
}
public void setpNumber(double no)
{
pNumber = no;
}
public void setUnits(double u)
{
Units = u;
}
public void setPrice(double p)
{
Price = p;
}
//getter methods
public String getName()
{
return Name;
}
public double getpNumber()
{
return pNumber;
}
public double getUnits()
{
return Units;
}
public double getPrice()
{
return Price;
}
public double calculateTotalPrice()
{
return (Units * Price);
}
public static double getCombinedCost(Items[] item)
{
double combined = 0;
for(int i =0; i < item.length; ++i)
{
combined = combined + item[i].calculateTotalPrice();
}
return combined;
}
}
You simply declare a method with the same signature as the method in the parent class. So yours would look like:
package inventory3;
public class ItemDetails extends Items {
private String Name;
private double pNumber, Units, Price;
public ItemDetails(String Name, double pNumber, double Units, double Price) {
this.Name = Name;
this.pNumber = pNumber;
this.Units = Units;
this.Price = Price;
}
// getters and setters....
// The #Override is optional, but recommended.
#Override
public double calculateTotalPrice() {
return Units * Price * 1.05; // From my understanding this is what you want to do
}
}